Java FileOutputStream Class
The data is written to a file by the FileOutputStream. The FileOutputStream class in Java supports files. It's a part of the java.io package. Bytes are used to store the data. When we need to write data into a newly generated file, we use the FileOutputStream class. A constructor to create a file is also provided by the FileOutputStream class. It is used for files that are already existing.
The constructor's signature is:
public FileOutputStream(String name, boolean append) throws FileNotFoundException
where name is the file name, and
append: If true, the byte will be written to the end of the file, not in the beginning.
Example
import java.io.FileOutputStream;
import java.util.Scanner;
public class fc_example2
{
public static void main(String args[])
{
try
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String file = sc.nextLine();
FileOutputStream fos=new FileOutputStream(file, 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();
System.out.println("File is saved.");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output

Must Read Type Conversion in Java
Java File.createFile() method
The File.createFile() function is part of the java.nio.file package's File class. It includes file support. The nio package is designed to work with buffers. A new, empty file can also be created using the createFile() function. When utilising this strategy, we don't need to close the resources. This is a benefit.
public static Path createFile(Path, Attribute) throws IOException
where, Path is the path to the file, and
The Attribute is an optional list of file attributes.
The function returns the file.
The example below also creates a new, empty file. Paths.get() is a static method in the Paths class (java.nio.file.Paths) that we use to build a Path instance. Take note of the following:
Path path = Paths.get("C:\\Users\\panis\\samplefile.txt");
In the above line, Paths is a class, and Path is an interface. Both are part of the same product. The Path Instance is created using the Paths.get() function.
Example
import java.io.IOException;
import java.nio.file.*;
public class fc_example3
{
public static void main(String[] args)
{
Path path = Paths.get("C:\\Users\\panis\\samplefile.txt"); //creation of Path instance
try
{
Path p= Files.createFile(path); //creates file at the specified location
System.out.println("File Created at Path: " + p);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Output

Practice it on online java compiler for better understanding.
Must Read Static Blocks In Java, Why is Java Platform Independent
FAQs
-
What are exceptions in Java?
An exception is an unwelcome or unexpected occurrence that occurs during the execution of a programme, i.e. at run time, and disturbs the program's usual flow of instructions. The application can detect and handle exceptions. When a method throws an exception, it creates an object. The exception object is the term given to this object. It contains details about the exception, such as the name and description of the error and the program's state when the error occurred.
-
What is Exception handling?
Exception Handling in Java is one of the most effective ways to manage runtime failures while maintaining the application's normal flow. ClassNotFoundException, IOException, SQLException, RemoteException, and other runtime errors are handled by Java Exception Handling.
-
Explain try-catch in Java.
The try block in Java is used to contain code that could potentially throw an exception. It has to be utilised as a part of the technique. The rest of the block code will not execute if an exception occurs at a specific statement in the try block. As a result, code that does not throw an exception should not be kept in a try block. A catch or a finally block must be used after a try block in Java.
The Java catch block is utilised to handle the exception by declaring the kind of exception within the parameter. The parent class exception (i.e., exception) or the generated exception type must be defined. However, stating the type of exception generated is advisable. Only after the try block should the catch block be utilised. With a single try block, you can use many catch blocks.
-
What are packages?
In Java, a package is a container for a collection of classes, sub-packages, and interfaces. Packages are used for the following purposes:
→ Packages are used for keeping name problems at bay.
→ They make it easier to search for, locate, and use classes, interfaces, enumerations, and annotations.
→ They provide controlled access: package-level access control is available in both protected and default modes. Classes in the same package and its subclasses can access a protected member. Only classes in the same package have access to a default member (with no access specifier).
→ Packages are a type of data encapsulation (or data-hiding).
Key Takeaways
In this article, we learned how to create a file in Java. We saw three ways to create a file, namely, using File.createNewFile() method, using FileOutputStream class and using File.createFile() method.
We hope this blog has helped you enhance your knowledge. If you want to learn more, check out our articles on File Input/Output - Coding Ninjas Coding Ninjas Studio and File Input Stream class - Coding Ninjas Coding Ninjas Studio. Do upvote our blog to help other ninjas grow.
Head over to our practice platform Coding Ninjas Studio to practise top problems, attempt mock tests, read interview experiences, and much more!
Happy Reading!