Java : Read and Write to a file

The code below show you how you can read a file using Java:

Path path = Paths.get("myFile.txt");
if(Files.exists(path)){
File file = path.toFile();
try(BufferedReader in = new BufferedReader(
new FileReader(file))){
String line = in.readLine();
while(line != null){
System.out.println(line);
line = in.readLine();
}
} catch(IOException ex){
//do something with exception
}
}
view raw java_read_file hosted with ❤ by GitHub


Code for Writing to a file:

Path path = Paths.get("myFile.txt");
if(Files.exists(path)){
File file = path.toFile();
try(PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(file)))){
out.print("something interesting...");
} catch(IOException ex){
//do something with exception
}
}
view raw java_write_file hosted with ❤ by GitHub


By using a buffered stream, you can dramatically improve the performance of I/O operations. We also use the try-with-resources for automatically closes the object and releases its resources.

Comments

Popular posts from this blog

Spring JPA : Using Specification with Projection

Chip input using Reactive Form