There are two ways to read and write files in Java:
Using the FileInputStream and FileOutputStream classes: These classes provide a low-level interface for reading and writing files.
Using the Scanner and PrintWriter classes: These classes provide a higher-level interface for reading and writing files.
Here is a sample code that shows how to read and write a file using the FileInputStream and FileOutputStream classes:
Java
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileIOExample
{
public static void main(String[] args) throws Exception
{
// Create a FileInputStream object for the file that we want to read.
FileInputStream inputStream = new FileInputStream("myfile.txt");
// Create a FileOutputStream object for the file that we want to write to.
FileOutputStream outputStream = new FileOutputStream("myfile_copy.txt");
// Read the contents of the file and write them to the new file.
int data;
while ((data = inputStream.read()) != -1)
{
outputStream.write(data);
}
// Close the streams.
inputStream.close();
outputStream.close();
}
}
Here is a sample code that shows how to read and write files using the Scanner and PrintWriter classes:
Java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class FileIOExample
{
public static void main(String[] args) throws FileNotFoundException
{
// Create a Scanner object for the file that we want to read.
Scanner scanner = new Scanner(new File("myfile.txt"));
// Create a PrintWriter object for the file that we want to write to.
PrintWriter writer = new PrintWriter("myfile_copy.txt");
// Read the contents of the file and write them to the new file.
while (scanner.hasNextLine())
{
writer.println(scanner.nextLine());
}
// Close the streams.
scanner.close();
writer.close();
}
}
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
There are two ways to read and write files in Java:
Here is a sample code that shows how to read and write a file using the FileInputStream and FileOutputStream classes:
Java
Here is a sample code that shows how to read and write files using the Scanner and PrintWriter classes:
Java