java文件读写大全

使用Java操作文本文件的方法详解
摘要: 最初java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类
最初java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了Reader和Writer两个类,这两个类都是抽象类,Writer中 write(char[] ch,int off,int
length),flush()和close()方法为抽象方法,Reader中read(char[] ch,int off,int length)和close()方法是抽象方法。子类应该分别实现他们。
  当我们读写文本文件的时候,采用Reader是非常方便的,比如FileReader,InputStreamReader和BufferedReader。其中最重要的类是InputStreamReader,
它是字节转换为字符的桥梁。你可以在构造器重指定编码的方式,如果不指定的话将采用底层操作系统的默认编码方式,例如GBK等。当使用FileReader读取文件
的时候。
  1. FileReader fr new FileReader("ming.txt");  
  2. int ch 0;  
  3. while((ch fr.read())!=-1  
  4.  
  5. System.out.print((char)ch);  
  6.  

其中read()方法返回的是读取得下个字符。当然你也可以使用read(char[] ch,int off,int length)这和处理二进制文件的时候类似,不多说了。如果使用
InputStreamReader来读取文件的时候
while((ch = isr.read())!=-1)
{
System.out.print((char)ch);
}
这和FileReader并没有什么区别,事实上在FileReader中的方法都是从InputStreamReader中继承过来的。read()方法是比较好费时间的,如果为了提高效率
我们可以使用BufferedReader对Reader进行包装,这样可以提高读取得速度,我们可以一行一行的读取文本,使用readLine()方法。
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("ming.txt")));
String data = null;
while((data = br.readLine())!=null)
{
System.out.println(data);
}
当你明白了如何用Reader来读取文本文件的时候那么用Writer写文件同样非常简单。有一点需要注意,当你写文件的时候,为了提高效率,写入的数据会先
放入缓冲区,然后写入文件。因此有时候你需要主动调用flush()方法。与上面对应的写文件的方法为:
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
  1. FileWriter fw new FileWriter("hello.txt");  
  2. String "hello world";  
  3. fw.write(s,0,s.length());  
  4. fw.flush();  
  5. OutputStreamWriter osw new OutputStreamWriter(new FileOutputStream("hello2.txt"));  
  6. osw.write(s,0,s.length());  
  7. osw.flush();  
  8. PrintWriter pw new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3.txt")),true);  
  9. pw.println(s);  

不要忘记用完后关闭流!下面是个小例子,帮助新手理解。其实有的时候java的IO系统是需要我们多记记的,不然哪天就生疏了。


  1. import java.io.*;  
  2. public class TestFile2  
  3.  
  4. public static void main(String[] args) throws IOException  
  5.  
  6. FileReader fr new FileReader("ming.txt");  
  7. char[] buffer new char[1024];  
  8. int ch 0;  
  9. while((ch fr.read())!=-1  
  10.  
  11. System.out.print((char)ch);  
  12.  
  13.   InputStreamReader isr new InputStreamReader(new FileInputStream("ming.txt"));  
  14. while((ch isr.read())!=-1)  
  15.  
  16. System.out.print((char)ch);  
  17.  
  18.   BufferedReader br new BufferedReader(new InputStreamReader(new FileInputStream("ming.txt")));  
  19. String data null;  
  20. while((data br.readLine())!=null)  
  21.  
  22. System.out.println(data);  
  23.  
  24.   FileWriter fw new FileWriter("hello.txt");  
  25. String "hello world";  
  26. fw.write(s,0,s.length());  
  27. fw.flush();  
  28.   OutputStreamWriter osw new OutputStreamWriter(new FileOutputStream("hello2.txt"));  
  29. osw.write(s,0,s.length());  
  30. osw.flush();  
  31.   PrintWriter pw new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3.txt")),true);  
  32. pw.println(s);  
  33.   fr.close();  
  34. isr.close();  
  35. br.close();  
  36. fw.close();  
  37. osw.close();  
  38. pw.close();  
  39.  
  40.  

java中多种方式读文件
一、多种方式读文件内容。
1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容
4、随机读取文件内容

·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
  1. import java.io.BufferedReader;  
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.FileReader;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.InputStreamReader;  
  8. import java.io.RandomAccessFile;  
  9. import java.io.Reader;  
  10. public class ReadFromFile  
  11.   
  12. public static void readFileByBytes(String fileName){  
  13. File file new File(fileName);  
  14. InputStream in null;  
  15. try  
  16. System.out.println("以字节为单位读取文件内容,一次读一个字节:");  
  17. // 一次读一个字节  
  18. in new FileInputStream(file);  
  19. int tempbyte;  
  20. while((tempbyte=in.read()) != -1){  
  21. System.out.write(tempbyte);  
  22.  
  23. in.close();  
  24. catch (IOException e)  
  25. e.printStackTrace();  
  26. return;  
  27.  
  28. try  
  29. System.out.println("以字节为单位读取文件内容,一次读多个字节:");  
  30. //一次读多个字节  
  31. byte[] tempbytes new byte[100];  
  32. int byteread 0;  
  33. in new FileInputStream(fileName);  
  34. ReadFromFile.showAvailableBytes(in);  
  35. //读入多个字节到字节数组中,byteread为一次读入的字节数  
  36. while ((byteread in.read(tempbytes)) != -1){  
  37. System.out.write(tempbytes, 0, byteread);  
  38.  
  39. catch (Exception e1)  
  40. e1.printStackTrace();  
  41. finally  
  42. if (in != null){  
  43. try  
  44. in.close();  
  45. catch (IOException e1)  
  46.  
  47.  
  48.  
  49.  
  50.   
  51. public static void readFileByChars(String fileName){  
  52. File file new File(fileName);  
  53. Reader reader null;  
  54. try  
  55. System.out.println("以字符为单位读取文件内容,一次读一个字节:");  
  56. // 一次读一个字符  
  57. reader new InputStreamReader(new FileInputStream(file));  
  58. int tempchar;  
  59. while ((tempchar reader.read()) != -1){  
  60. //对于windows下,rn这两个字符在一起时,表示一个换行。  
  61. //但如果这两个字符分开显示时,会换两次行。  
  62. //因此,屏蔽掉r,或者屏蔽n。否则,将会多出很多空行。  
  63. if (((char)tempchar) != 'r'){  
  64. System.out.print((char)tempchar);  
  65.  
  66.  
  67. reader.close();  
  68. catch (Exception e)  
  69. e.printStackTrace();  
  70.  
  71. try  
  72. System.out.println("以字符为单位读取文件内容,一次读多个字节:");  
  73. //一次读多个字符  
  74. char[] tempchars new char[30];  
  75. int charread 0;  
  76. reader new InputStreamReader(new FileInputStream(fileName));  
  77. //读入多个字符到字符数组中,charread为一次读取字符数  
  78. while ((charread reader.read(tempchars))!=-1){  
  79. //同样屏蔽掉r不显示  
  80. if ((charread == tempchars.length)&&(tempchars[tempchars.length-1] != 'r')){  
  81. System.out.print(tempchars);  
  82. }else{  
  83. for (int i=0; i<charread; i++){  
  84. if(tempchars[i] == 'r'){  
  85. continue;  
  86. }else{  
  87. System.out.print(tempchars[i]);  
  88.  
  89.  
  90.  
  91.  
  92. catch (Exception e1)  
  93. e1.printStackTrace();  
  94. }finally  
  95. if (reader != null){  
  96. try  
  97. reader.close();  
  98. catch (IOException e1)  
  99.  
  100.  
  101.  
  102.  
  103.   
  104. public static void readFileByLines(String fileName){  
  105. File file new File(fileName);  
  106. BufferedReader reader null;  
  107. try  
  108. System.out.println("以行为单位读取文件内容,一次读一整行:");  
  109. reader new BufferedReader(new FileReader(file));  
  110. String tempString null;  
  111. int line 1;  
  112. //一次读入一行,直到读入null为文件结束  
  113. while ((tempString reader.readLine()) != null){  
  114. //显示行号  
  115. System.out.println("line line ": tempString);  
  116. line++;  
  117.  
  118. reader.close();  
  119. catch (IOException e)  
  120. e.printStackTrace();  
  121. finally  
  122. if (reader != null){  
  123. try  
  124. reader.close();  
  125. catch (IOException e1)  
  126.  
  127.  
  128.  
  129.  
  130.   
  131. public static void readFileByRandomAccess(String fileName){  
  132. RandomAccessFile randomFile null;  
  133. try  
  134. System.out.println("随机读取一段文件内容:");  
  135. // 打开一个随机访问文件流,按只读方式  
  136. randomFile new RandomAccessFile(fileName, "r");  
  137. // 文件长度,字节数  
  138. long fileLength randomFile.length();  
  139. // 读文件的起始位置  
  140. int beginIndex (fileLength 4) 0;  
  141. //将读文件的开始位置移到beginIndex位置。  
  142. randomFile.seek(beginIndex);  
  143. byte[] bytes new byte[10];  
  144. int byteread 0;  
  145. //一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。  
  146. //将一次读取的字节数赋给byteread  
  147. while ((byteread randomFile.read(bytes)) != -1){  
  148. System.out.write(bytes, 0, byteread);  
  149.  
  150. catch (IOException e){  
  151. e.printStackTrace();  
  152. finally  
  153. if (randomFile != null){  
  154. try  
  155. randomFile.close();  
  156. catch (IOException e1)  
  157.  
  158.  
  159.  
  160.  
  161.   
  162. private static void showAvailableBytes(InputStream in){  
  163. try  
  164. System.out.println("当前字节输入流中的字节数为:" in.available());  
  165. catch (IOException e)  
  166. e.printStackTrace();  
  167.  
  168.  
  169. public static void main(String[] args)  
  170. String fileName "C:/temp/newTemp.txt";  
  171. ReadFromFile.readFileByBytes(fileName);  
  172. ReadFromFile.readFileByChars(fileName);  
  173. ReadFromFile.readFileByLines(fileName);  
  174. ReadFromFile.readFileByRandomAccess(fileName);  
  175.  
  176.  
  177. 二、将内容追加到文件尾部  
  178. import java.io.FileWriter;  
  179. import java.io.IOException;  
  180. import java.io.RandomAccessFile;  
  181.   
  182. public class AppendToFile  
  183.   
  184. public static void appendMethodA(String fileName,  
  185.   
  186. String content){  
  187. try  
  188. // 打开一个随机访问文件流,按读写方式  
  189. RandomAccessFile randomFile new RandomAccessFile(fileName, "rw");  
  190. // 文件长度,字节数  
  191. long fileLength randomFile.length();  
  192. //将写文件指针移到文件尾。  
  193. randomFile.seek(fileLength);  
  194. randomFile.writeBytes(content);  
  195. randomFile.close();  
  196. catch (IOException e){  
  197. e.printStackTrace();  
  198.  
  199.  
  200.   
  201. public static void appendMethodB(String fileName, String content){  
  202. try  
  203. //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件  
  204. FileWriter writer new FileWriter(fileName, true);  
  205. writer.write(content);  
  206. writer.close();  
  207. catch (IOException e)  
  208. e.printStackTrace();  
  209.  
  210.  
  211. public static void main(String[] args)  
  212. String fileName "C:/temp/newTemp.txt";  
  213. String content "new append!";  
  214. //按方法A追加文件  
  215. AppendToFile.appendMethodA(fileName, content);  
  216. AppendToFile.appendMethodA(fileName, "append end. n");  
  217. //显示文件内容  
  218. ReadFromFile.readFileByLines(fileName);  
  219. //按方法B追加文件  
  220. AppendToFile.appendMethodB(fileName, content);  
  221. AppendToFile.appendMethodB(fileName, "append end. n");  
  222. //显示文件内容  
  223. ReadFromFile.readFileByLines(fileName);  
  224.  
  225. }

come from :http://blog.sina.com.cn/s/blog_5e2c3a010100sgoy.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值