Skip to content

Instantly share code, notes, and snippets.

@kenorb
Last active August 29, 2015 14:04
Show Gist options
  • Save kenorb/3160154faee2db8a51fd to your computer and use it in GitHub Desktop.
Save kenorb/3160154faee2db8a51fd to your computer and use it in GitHub Desktop.
File Handling Demo
/*
* File Handling Demo
*
* Is all about reading and writing activities over file system (java.io).
* Streams provide communication channels between communication participants.
*
* Type of stream classes:
* * Byte Stream classes:
* - do not support Unicode
* * Character Stream classes:
* - they do support Unicode
* Both:
* - support for InputStream & OutputStream (FileInputStream, ObjectInputStream)
* - support for Reader & Writer
*
* Usage:
* javac FileHandlingDemo.java
* java WriteToFileDemo
* java ReadFromFileDemo
* java FileReaderDemo
*/
import java.io.*;
class WriteToFileDemo {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("NewFile.txt");
// FileOutputStream fos = new FileOutputStream("NewFile.txt", true); // Append mode.
fos.write("My message" . getBytes()); // getBytes() - Encodes String into a sequence of bytes
System.out.println("File created.");
}
}
class ReadFromFileDemo {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("NewFile.txt");
int ch;
while ((ch = fis.read()) != -1) {
System.out.print((char)ch);
} // end of while
}
}
class FileReaderDemo {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("NewFile.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment