JAVA文件操作之读/写文件

 
  
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最常用,大文件可以有效提高效率。

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

待续…………

转载于:https://www.cnblogs.com/binbinjava/archive/2011/03/18/1987838.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值