In Java, files can be processed by either streams or buffers.
java.io Library – helps in file processing by streams, where this is a classic one.
java.nio Library – helps in file processing by buffers, using nio(non blocking IO) is the latest one supported from Java 1.5
Streams are used to process files in Java.io package.
Byte Streams – FileInputStream/FileOutputStream, BufferedInputStream etc.,
Character Streams – FileReader/FileWriter etc.,
The following example provides an idea of how files can be read/write using byte streams.
Read File using FileInputStream in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class ReadFileExample { public static void main(String[] args) { ReadFileExample readFileExample = new ReadFileExample(); byte[] content = readFileExample.getContentOfFile("/Users/tutorialflow/Documents/javadocfile.txt"); System.out.println("Content:"); System.out.println(new String(content)); } public byte[] getContentOfFile(String file) { File fileName = new File(file); byte content[] = null; System.out.println("Current File Path:"+fileName.getAbsolutePath()); try { FileInputStream fis = new FileInputStream(fileName); content = new byte[fis.available()]; fis.read(content); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return content; } } |
Result:
1 |
<br>Current File Path: /Users/tutorialflow/Documents/javadocfile.txt<br>Content: <br>This is sample content present in the file |
Write content into File using FileOutpuStream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class WriteFileExample { public static void main(String[] args) { WriteFileExample writeFileExample = new WriteFileExample(); String filePath = "/Users/tutorialflow/Documents/javadocfile2.txt"; writeFileExample.writeContentIntoFile("This is a SampleContent to Write...!!",filePath); } public void writeContentIntoFile(String content, String filePath) { File fileName = new File(filePath); boolean append = false; try { FileOutputStream fout = new FileOutputStream(fileName, append); fout.write(content.getBytes()); fout.flush(); fout.close(); System.out.println("File Successfully Updated..."); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } |
Result:
1 |
File Successfully Updated... |