Two class in one java file

Two public classes in one file java

When we initialize File class object, we provide the file name and then we can call createNewFile() method of the File class to Create a new File in Java. In the following example, we have created a file using FileOutputStream. Output Java File.createFile() method The File.createFile() is a method of File class which belongs to java.nio.file package.

Two public classes in one file java

Ok, this might be kiddies question in java. We can’t define two public classes in one File. But, in one of the examples from the book SCJP study guide, this example was mentioned:

public abstract class A < public abstract void show(String data); >public class B extends A < public void show(String data)< System.out.println("The string data is "+data); >public static void main(String [] args) < B b = new B(); b.show("Some sample string data"); >> 

When I copy pasted this into netbeans immediately compile error was thrown, that public class A should me mentioned in separate file. Is that example from SCJP styudy guide really wrong? Also in some of the mock test I found many questions having such pattern but in none of the options was a compiler error was mentioned. Getting worried here

yes, 2 top level public classes are not allowed in one file

Well, if one is being so picky: you can have multiple classes defined with a public modifier in the same file, that is, using the static nested(inner) class. like this:

Yes you can have two classes in the same file. You can have them by removing the public access modifier from both the class name, like shown below,

abstract class A < public abstract void show(String data); >class B extends A < public void show(String data)< System.out.println("The string data is "+data); >public static void main(String [] args) < B b = new B(); b.show("Some sample string data"); >> 

you can make 2 public classes in one file , inside a class that contains them .

it’s also recommended to add «static» for them , if you do not need any reference to the container class .

Java FileWriter (With Examples), In order to create a file writer, we must import the Java.io.FileWriter package first. Once we import the package, here is how we can create the file writer. 1. Using the name of the file FileWriter output = new FileWriter (String name); Here, we have created a file writer that will be linked to the file specified by the name. 2.

Java File Class

In this tutorial, we will learn about Java File and its various operations with the help of examples.

The File class of the java.io package is used to perform various operations on files and directories.

There is another package named java.nio that can be used to work with files. However, in this tutorial, we will focus on the java.io package.

File and Directory

A file is a named location that can be used to store related information. For example,

main.java is a Java file that contains information about the Java program.

A directory is a collection of files and subdirectories. A directory inside a directory is known as subdirectory.

Create a Java File Object

To create an object of File , we need to import the java.io.File package first. Once we import the package, here is how we can create objects of file.

// creates an object of File using the path File file = new File(String pathName); 

Here, we have created a File Object named file . The object can be used to work with files and directories.

Читайте также:  Discord js typescript template

Note : In Java, creating a file object does not mean creating a file. Instead, a File object is an abstract representation of the file or directory pathname (specified in the parenthesis).

Java File Operation Methods

Operation Method Package
To create file createNewFile() java.io.File
To read file read() java.io.FileReader
To write file write() java.io.FileWriter
To delete file delete() java.io.File
Java create files

To create a new file, we can use the createNewFile() method. It returns

  • true if a new file is created.
  • false if the file already exists in the specified location.
Example: Create a new File
// importing the File class import java.io.File; class Main < public static void main(String[] args) < // create a file object for the current location File file = new File("newFile.txt"); try < // trying to create a file based on the object boolean value = file.createNewFile(); if (value) < System.out.println("The new file is created."); >else < System.out.println("The file already exists."); >> catch(Exception e) < e.getStackTrace(); >> > 

In the above example, we have created a file object named file . The file object is linked with the specified file path.

File file = new File("newFile.txt"); 

Here, we have used the file object to create the new file with the specified path.

If newFile.txt doesn’t exist in the current location , the file is created and this message is shown.

However, if newFile.txt already exists , we will see this message.

Java read files

To read data from the file, we can use subclasses of either InputStream or Reader.

Example: Read a file using FileReader

Suppose we have a file named input.txt with the following content.

This is a line of text inside the file. 

Now let’s try to read the file using Java FileReader .

// importing the FileReader class import java.io.FileReader; class Main < public static void main(String[] args) < char[] array = new char[100]; try < // Creates a reader using the FileReader FileReader input = new FileReader("input.txt"); // Reads characters input.read(array); System.out.println("Data in the file:"); System.out.println(array); // Closes the reader input.close(); >catch(Exception e) < e.getStackTrace(); >> > 
Data in the file: This is a line of text inside the file. 

In the above example, we have used created an object of FileReader named input. It is now linked with the input.txt file.

FileReader input = new FileReader("input.txt"); 

To read the data from the input.txt file, we have used the read() method of FileReader .

Java write to files

To write data to the file, we can use subclasses of either OutputStream or Writer.

Example: Write to file using FileWriter
// importing the FileWriter class import java.io.FileWriter; class Main < public static void main(String args[]) < String data = "This is the data in the output file"; try < // Creates a Writer using FileWriter FileWriter output = new FileWriter("output.txt"); // Writes string to the file output.write(data); System.out.println("Data is written to the file."); // Closes the writer output.close(); >catch (Exception e) < e.getStackTrace(); >> > 
Data is written to the file. 

In the above example, we have created a writer using the FileWriter class. The writer is linked with the output.txt file.

FileWriter output = new FileWriter("output.txt"); 

To write data to the file, we have used the write() method .

Here when we run the program, the output.txt file is filled with the following content.

This is the data in the output file. 
Java delete files

We can use the delete() method of the File class to delete the specified file or directory. It returns

Note : We can only delete empty directories.

Example: Delete a file
import java.io.File; class Main < public static void main(String[] args) < // creates a file object File file = new File("file.txt"); // deletes the file boolean value = file.delete(); if(value) < System.out.println("The File is deleted."); >else < System.out.println("The File is not deleted."); >> > 

In the above example, we have created an object of File named file. The file now holds the information about the specified file.

File file = new File("file.txt"); 

Here we have used the delete() method to delete the file specified by the object.

Читайте также:  Python wait for file lock

Related Examples

JavaMail Example — Send Mail in Java using SMTP, To send a file as attachment, we need to create an object of javax.mail.internet.MimeBodyPart and javax.mail.internet.MimeMultipart. First add the body part for the text message in the email and then use FileDataSource to attach the file in second part of the multipart body. The method looks like below.

How to Create a File in Java

In Java, creating a file is easy by using pre-defined classes and packages. There are three ways to create a file.

  • Using File.createNewFile() method
  • Using FileOutputStream class
  • Using File.createFile() method

Java File.createNewFile() method

The File.createNewFile() is a method of File class which belongs to a java.io package. It does not accept any argument. The method automatically creates a new, empty file. The method returns a boolean value:

When we initialize File class object, we provide the file name and then we can call createNewFile() method of the File class to Create a new File in Java.

The File.createNewFile() method throws java.io.IOException if an I/O error occurred. It also throws SecurityException if a security manager exists and its SecurityManager.checkWriter(java.lang.String) method denies write access to the file. The signature of the method is:

public boolean createNewFile() throws IOException

We can pass the file name or absolute path or relative path as an argument in the File class object. For a non-absolute path, File object tries to locate the file in the current directory.

The following example creates a new, empty text file. The first run creates music.txt successfully while on the second run it failed. We can create any type of file by changing the file extension only.

import java.io.File; import java.io.IOException; public class CreateFileExample1 < public static void main(String[] args) < File file = new File("C:\\demo\\music.txt"); //initialize File object and passing path as argument boolean result; try < result = file.createNewFile(); //creates a new file if(result) // test if successfully created a new file < System.out.println("file created "+file.getCanonicalPath()); //returns the path string >else < System.out.println("File already exist at location: "+file.getCanonicalPath()); >> catch (IOException e) < e.printStackTrace(); //prints exception if any >> >

When file does not exists.

How to Create a File in Java

How to Create a File in Java1

Java FileOutputStream

A file output stream writes data to a file. Java FileOutputStream class also provide support for files. It belongs to the java.io package. It stores the data into bytes. We use FileOutputStream class when we need to write some data into the created file. The FileOutputStream class provides a constructor to create a file. The signature of the constructor is:

public FileOutputStream(String name, boolean append) throws FileNotFoundException

name: is the file name

append: if true, byte will be written to the end of the file, not in the beginning.

In the following example, we have created a file using FileOutputStream.

import java.io.FileOutputStream; import java.util.Scanner; public class CreateFileExample < public static void main(String args[]) < try < Scanner sc=new Scanner(System.in); //object of Scanner class System.out.print("Enter the file name: "); String name=sc.nextLine(); //variable name to store the file name FileOutputStream fos=new FileOutputStream(name, true); // true for append mode System.out.print("Enter file content: "); String str=sc.nextLine()+"\n"; //str stores the string which we have entered byte[] b= str.getBytes(); //converts string into bytes fos.write(b); //writes bytes into file fos.close(); //close the file System.out.println("file saved."); >catch(Exception e) < e.printStackTrace(); >> >

How to Create a File in Java2

Java File.createFile() method

The File.createFile() is a method of File class which belongs to java.nio.file package. It also provides support for files. The nio package is buffer-oriented. The createFile() method is also used to create a new, empty file. We don’t need to close the resources when using this method. It is an advantage. The signature of the method is:

public static Path createFile(Path, Attribute) throws IOException

Path: The path of the file.

Читайте также:  Тег IMG, атрибут border

Attribute: An optional list of file attributes.

The method returns the file.

The following example also creates a new, empty file. We create a Path instance using a static method in the Paths class (java.nio.file.Paths) named Paths.get(). Notice the following statement:

Path path = Paths.get(«C:\\demo\\javaprogram.txt»);

In the above line Path is an interface and Paths is a class. Both belongs to same package. The Paths.get() method creates the Path Instance.

import java.io.IOException; import java.nio.file.*; public class CreateFileExample3 < public static void main(String[] args) < Path path = Paths.get("C:\\demo\\javaprogram.txt"); //creates Path instance try < Path p= Files.createFile(path); //creates file at specified location System.out.println("File Created at Path: "+p); >catch (IOException e) < e.printStackTrace(); >> >

How to Create a File in Java3

How to Encrypt or Decrypt a File in Java?, 2 Answers. You simply have muddled your files. This code works using the DER files generated from openssl as described in the article you linked: FileEncryption secure = new FileEncryption (); // Encrypt code < File encryptFile = new File ("encrypt.data"); File publicKeyData = new File ("public.der"); File originalFile = …

Источник

Multiple Classes in One File in Java

Multiple Classes in One File in Java

  1. Use the Nested Classes to Have Multiple Classes in a Single File in Java
  2. Use Multiple Non-Nested Classes in a Single File in Java

We will discuss multiple classes in a single file in Java in this article.

There are many ways to declare multiple classes in one single file. We will be discussing two standard ways of implementing this.

Use the Nested Classes to Have Multiple Classes in a Single File in Java

In this method, the classes are defined within the class. This method enables us to logically group the classes that are to be only used in one place.

These are divided into two categories. First is the static nested class that is declared static, and the other is the inner class of the non-static type.

The code below demonstrates this method.

class Outer_Class   // static member  static int x = 20;   // instance(non-static) member  int y = 20;  private static int outer_private = 40;   // static nested class  static class StaticNestedClass    void display()    System.out.println("outer_x = " + x);  System.out.println("outer_private = " + outer_private);  >  > >  public class NestedDemo   public static void main(String[] args)    // accessing a static nested class  Outer_Class.StaticNestedClass nestedObject = new Outer_Class.StaticNestedClass();   nestedObject.display();   > > 
outer_x = 20 outer_private = 40 

Use Multiple Non-Nested Classes in a Single File in Java

We can also have multiple non-nested classes in a single file in Java.

We will understand this better with the following example.

public class Phone   Phone()   System.out.println("Constructor of phone class.");  >  void phone_method()   System.out.println("Phone battery is low");  >  public static void main(String[] args)   Phone p = new Phone();  Laptop l = new Laptop();  p.phone_method();  l.laptop_method();  > > class Laptop   Laptop()   System.out.println("Constructor of Laptop class.");  >  void laptop_method()   System.out.println("Laptop battery is low");  > > 
Constructor of phone class. Constructor of Laptop class. Phone battery is low Laptop battery is low 

In the above example, the program consists of two classes, the first is the Phone class and the second is the Laptop class.

Both the classes have constructors and a method for executing a function. When we run our program, two .class files are created for both classes. We can reuse the .class file again without recompiling the code. In the output, we can see our code has been executed successfully.

Related Article — Java Class

Copyright © 2023. All right reserved

Источник

Оцените статью