好久之前就学习Java 的IO包,但实际上对输入输出流一点都不了解,现在几乎是看见一个文件读取就得记一记,唉,得经常使用才好,要不估计就什么好处都没有,悲催啊,好了,废话不多说,上代码,主要是基本文件的读取和复制
package com.bird.one; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import org.junit.Test; /** * @category 从文件中读取数据 * @author Bird * */ public class ListFiles { @Test public void test(){//基本的读取文本文件内容 FileReader file; BufferedReader reader = null; String oneLine; System.out.println("读取" + " D盘下的test.xml"); try { file = new FileReader("d://x.txt"); reader = new BufferedReader(file); while((oneLine = reader.readLine())!= null) System.out.println(oneLine); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } @Test public void test1(){//将文件的内容复制到另一个文件中去 BufferedReader reader = null; PrintWriter writer = null; int count = 0; String line; try { reader = new BufferedReader(new FileReader("d://1.txt")); writer = new PrintWriter("d://2.txt"); while((line = reader.readLine()) != null){ writer.write(++count +"\t"); writer.write(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(reader != null)//一定注意要关闭输入输出流,否则无法将数据缓冲流打入到文本文件中 try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(writer != null) writer.close(); } }