1 package cn.com.test;
2 /*
3 * 读取文件:
4 * 1.FileReader
5 * 2.InputStreamReader(FileInputStream)
6 * 3.BufferReader()
7 * 写文件
8 * 1.FileWriter
9 * 2.OutputStreamWriter(FileOutputStream)
10 * 3.BufferReader()
11 * 4.RandomAccessFile()
12 */
13 import java.io.*;
14 import java.util.*;//获取键盘输入时用到
15
16 public class InputTest {
17 public static void main(String[] argu) throws FileNotFoundException{
18 /*这段代码是测试控制台输入输出,与文件无关,仅仅做个记录
19 Scanner in = new Scanner(System.in);
20 //get first input
21 System.out.print("What's your name?");
22 String name = in.nextLine();
23 //get second input
24 System.out.print("How old are you?");
25 int age = in.nextInt();
26 //display output on console
27 System.out.println("Hello,"+name+".Next year,you'll be:"+(age+1));
28 */
29 //file out&in
30 int ch = 0;
31 String reading = null;
32 String reading2 = null;
33 //Filereader read the file content
34 try{
35 //FileReader fr = new FileReader("F:\\111.txt");
36 BufferedReader bfr = new BufferedReader(new FileReader("F:\\111.txt"));
37 BufferedReader bfr2 = new BufferedReader(new InputStreamReader(new FileInputStream("F:\\111.txt")));
38 while((reading = bfr.readLine())!=null&&(reading2 = bfr2.readLine())!=null){//while(ch = bfr.read()!=-1){}
39 System.out.println(reading);
40 System.out.println(reading2);
41 }
42 bfr.close();
43 bfr2.close();
44 }
45
46 catch (IOException e) {
47 e.printStackTrace();
48 }
49
50 try{
51 // 用常规的方法读写普通文件会造成覆盖原内容
52 String strwrite= "love station,love people!1";
53 FileWriter fw = new FileWriter("F:\\222.txt");
54 fw.write(strwrite, 0, strwrite.length());
55 fw.flush();
56 fw.close();
57
58 strwrite = strwrite+"2";
59 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("F:\\222.txt"));
60 osw.write(strwrite,0 ,strwrite.length());
61 osw.flush();
62 osw.close();
63 //采用BufferWriter()包装流,避免频繁调用转换器;
64 strwrite = strwrite+"3";
65 BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("F:\\222.txt")));
66 bfw.write(strwrite, 0, strwrite.length());
67 bfw.close();
68 //采用RandomAccessFile读写可以解决覆盖问题
69 File file = new File("F:\\222.txt");
70 strwrite = strwrite+"4";
71 RandomAccessFile raf = new RandomAccessFile("F:\\222.txt","rw");
72 raf.seek(raf.length());//定位
73 raf.write(0x0A);
74 raf.writeBytes(strwrite);
75 raf.close();
76
77 }
78 catch (IOException e) {
79 e.printStackTrace();
80 }
81
82 }
83
84 }

API



对文件的读写,java提供了很多种方法,需要根据不同使用条件判断使用哪种方法最合适,其中BufferReader/BufferWriter最常用,大文件可以有效提高效率。

后面会记录按照不同单位(字符,字节,行等)读写文件;

待续…………

posted on 2011-03-18 11:05  aodixius  阅读(373)  评论(0编辑  收藏  举报