JAVA文件流的读写

版权声明:本文为博主原创文章,欢迎指正或者转载。 https://blog.csdn.net/ThinkPet/article/details/83893727
package trsdf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class FileStreamRW {

	public static void main(String[] args) {
		/*
		 * 写一个文件到磁盘
		 */
		//File f =new File("a.txt");//不指定绝对路径,则默认写入到项目工作空间目录下
		File f =new File("D:/a.txt");//绝对路径可以用单斜杠/  或双反斜杠\\
		
		try {
			// 构建FileOutputStream对象,文件不存在会自动新建
			FileOutputStream fop =new FileOutputStream(f);
			// 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk
			OutputStreamWriter writer =new OutputStreamWriter(fop, "utf-8");
			// 写入到缓冲区
			writer.append("这是一个测试文本");
			//换行
			writer.append("\r\n");
			// 写入到缓冲区
			writer.append("English12346");
			// 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入
			//writer.flush();
			//关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉
			writer.close();
			//关闭文件输出流,释放系统资源
			fop.close();
			System.out.println("文件"+f.getName()
			         +"\n已经写到磁盘"+f.getAbsolutePath()
			         +"\n文件大小"+f.length()+"字节");
		} catch (FileNotFoundException e) {
			System.out.println("找不到文件");
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			System.out.println("不支持修改编码");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("io异常");
			e.printStackTrace();
		}
		
		/*
		 * 把刚刚写到磁盘的文件读到控制台显示出来
		 */
		try {
			// 构建FileInputStream对象
			FileInputStream fip =new FileInputStream(f);
			// 构建InputStreamReader对象,编码与写入相同
			InputStreamReader reader=new InputStreamReader(fip,"utf-8");
			//使用线程安全的StringBuffer 接收输入流
			StringBuffer sbf =new StringBuffer();
			while(reader.ready()) {//判断输入流是否准备好
				sbf.append((char)reader.read());// 转成char加到StringBuffer对象中
			}
			//读到控制台显示出来
			System.out.println("\n\n显示文件内容:\n"+sbf.toString());
			// 关闭读取流
			reader.close();
			// 关闭输入流,释放系统资源
			fip.close();
		} catch (FileNotFoundException e) {
			System.out.println("找不到文件");
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			System.out.println("不支持修改编码");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("io异常");
			e.printStackTrace();
		}
		
		
		
	}

}

猜你喜欢

转载自blog.csdn.net/ThinkPet/article/details/83893727