Java Files and I/O
javaIn Java, the java.io
package provides classes and interfaces for reading and writing data to and from files.
Here are some common classes and methods for reading and writing text files:
FileReader
: Reads characters from a file.
BufferedReader
: Reads lines of text from a file.
FileWriter
: Writes characters to a file.
BufferedWriter
: Writes lines of text to a file.
Here is an example of how to read a text file in Java:
File file = new File("input.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
This example reads the file line by line and prints each line to the console.
To write to a text file, you can use a similar approach:
File file = new File("output.txt");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write("Hello, World!");
writer.newLine();
writer.write("This is a test.");
} catch (IOException e) {
e.printStackTrace();
}
This example writes two lines of text to the file.
The java.nio
package also provides classes for working with files, such as the Files class, which provides methods for
reading, writing, and manipulating files and directories.
Other Article on Tag java
- - after and before in java date
- - am pm java date format
- - apk minecraft java edition
- - as been blocked by CORS policy Response to preflight request doesn't pass access control check It does not have HTTP ok status
- - bubble sort in java
- - Can I compile and run a spring boot jar from inside another spring boot application
- - convert java date to localdate
- - design patterns in java
- - encrypt by java and decrypt by node
- - exception handling in java