java.io.InputStream
- java.io.FileInputStream
- java.io.FilterInputStream
- java.io.BufferedInputStream
When to use: Deal with charset problem (InputStream is byte-based, FileInputStream makes it char-based)
Example:
InputStreamReader isr = new InputStreamReader( new FileInputStream("test.txt"),"utf-8"); BufferedReader br = new BufferedReader(isr); String str = br.readLine(); br.close();
java.lang.Object
- java.io.Reader
- java.io.InputStreamReader
- java.io.FileReader
When to use: Usually this could be easier as we can use Scanner after JDK 1.5 (Be careful to charset problem)
Example:
FileReader fr = new FileReader("file.txt"); BufferedReader br = new BufferedReader(fr); Scanner sc = new Scanner(fr); int i = sc.nextInt(); String str = br.readLine(); br.close();
Writing:
The class hierachy is symmetrical to reading.
Example:
FileWriter fw = new FileWriter("test.txt"); fw.write("Something"); fw.close();
(Or PrintWriter can be used but it doesn't throw IOException)
OutputStreamWriter osw = new OutputStreamWriter( new FileOutputStream("file.txt"), "utf-8"); osw.write("Something"); osw.close();
No comments:
Post a Comment