Skip to content

fefong/java-fileReadWrite

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Java Reader and Write Files

Example Application: Reader (FileReader) and Write (FileWriter) files.

Read File

Imports

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

Check file exists

⚠️ Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.

File file = new File(FILE);

if (file.exists()) {
	//TODO
} else {
	//TODO
}

Read file

⚠️ Need add throws declaration or surround with try/catch;

String FILE = "YOUR_LOG.log";

FileReader reader = new FileReader(FILE);
BufferedReader buffer = new BufferedReader(reader);

String line = null;

while ((line = buffer.readLine()) != null) {
	//TODO
	System.out.printf("%s\n", line);
}

⚠️ Closes the stream and releases any system resources associated withit.

buffer.close();

See the implementation: project

Write File

Imports

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

Check file exists

⚠️ Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.

String FILE = "YOUR_LOG.log";

File file = new File(FILE);

if (file.exists()) {
	//TODO
} else {
	//TODO
}

Write File

⚠️ Need add throws declaration or surround with try/catch;

String content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

String FILE = "YOUR_LOG.log";
FileWriter writer = new FileWriter(FILE);
BufferedWriter buffer = new BufferedWriter(writer);

buffer.write(content);

System.out.println("Success! You file is saved!");

⚠️ Closes the stream and releases any system resources associated withit.

buffer.close();

See the implementation: project

Exceptions

  • IOException

Some links for more in depth learning