I/O操作主要是指使用Java进行输入,Java所有的I/O机制都是基于数据流进行输入输出,这些数据流表示了字符或者字节数据的流动序列。
主要是通过下面两个类实现对文件的输入输出操作:
FileInputStream 输入类
FileOutputStream输出类
可以参考 http://blog.csdn.net/hguisu/article/details/7418161 ,这篇文章写的挺详细。
下面代码是简单的一些对文件的操作:
1、读取TXT文件的两种方式:
/* * 第二种方式 按行读取 */ public void ReaderFile() { String paths = this.getClass().getResource("").getPath(); System.out.println(paths); String path = "E:\学习文档\一个程序员的奋斗史.txt"; File file = new File(path); if (file.exists()) { try { FileInputStream Input=new FileInputStream(file); //获取 StreamReader对象,对编码进行处理 InputStreamReader StreamReader=new InputStreamReader(Input,"UTF-8"); BufferedReader reader=new BufferedReader(StreamReader); String str=null; while (reader.readLine() != null) { str=reader.readLine(); System.out.println(str); } } catch (IOException e) { System.out.println("异常:"+e); } } } /* * 第二种方式 */ public void ReaderFile() { String paths = this.getClass().getResource("").getPath(); System.out.println(paths); String path = "E:\学习文档\一个程序员的奋斗史.txt"; File file = new File(path); if (file.exists()) { try { FileInputStream Input=new FileInputStream(file); //获取 StreamReader对象,对编码进行处理 byte[] buffer=new byte[Input.available()]; Input.read(buffer); String str=new String(buffer,"utf-8"); System.out.println(str); } catch (IOException e) { System.out.println("异常:"+e); } } }
2、写TXT文件
/* * 写文件 */ public void WriteFile() { //创建一个文本文件 File file=new File("E:\学习文档","测试文本.txt"); try { FileOutputStream output=new FileOutputStream(file); byte[] buffer="这是一个测试文本的内容".getBytes(); output.write(buffer); output.close(); System.out.println("OK"); } catch (IOException e) { System.out.println(e); } }
3、在文本的后面继续写入文字
//写文件 -- 继续下一行往下写 public void WriteLineFile() { File file=new File("E:\学习文档","wwj.txt"); try { if(!file.exists()) file.createNewFile(); FileInputStream input=new FileInputStream(file); byte[] buffer=new byte[input.available()]; //创建数组,大小为流的大小 input.read(buffer); //将原来的文件流加入到缓冲区 String content=new String(buffer,"utf-8")+"往下写下一行的内容------------------------ "; byte[] buffercontent=content.getBytes(); //将字符串转换为字节数组 FileOutputStream out=new FileOutputStream(file); out.write(buffercontent); //将缓冲区数据写入 out.close(); //关闭流 input.close(); System.out.println("完成"); } catch (IOException e) { System.out.println(e); } }
4、获取一个文件的数据,输出到指定的目录(主要是用于下载文件)
// 获取一个文件的数据,输出到另一个地方 public void GetWriteFile() { File Getfile = new File("E:\学习文档", "学通ASP.NET的24堂课.pdf"); try { // 获取文件输入流对象 FileInputStream input = new FileInputStream(Getfile); // 创建字节数组 大小为流的的长度 byte[] buffer = new byte[input.available()]; // 写入到缓冲区 input.read(buffer); // 获取输出对象 FileOutputStream output = new FileOutputStream("C:\Users\wwj\Desktop\24堂课.pdf"); output.write(buffer); output.close(); input.close(); System.out.println("输出成功"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }