数据流输出到文件流程:
1、新建文件对象:File f = new File("D:/a.txt");
2、构建文件输出流对象,如果不存在则新建文件: OutputStream output = new FileOutputStream(f);
3、将字符流转换为字节流:OutputStreamWriter write = new OutputStreamWriter(output,"utf-8");-----因为输出到文档的数据流是字节流。用utf-8的编码格式输出。
4、将字节转换为字符,输入缓冲区:write.append("中文输入!");
5、关闭写入流,同时将缓冲区的字节流写入文件:write.close();
6、关闭输出流,同时释放系统资源:output.close();
从文件读取数据到系统流程:
1、构建文件对象:File f = new File("D:/a.txt");
2、构建文件输入流对象,不存在则返回错误:FileInputStream fip = new FileInputStream(f);
3、将字符流转换为字节流,需要采用相同的utf-8编码才能解码:InputStreamReader reader = new InputStreamReader(fip,"utf-8");
4、读入数据存储在字符串对象中:
StringBuffer sb = new StringBuffer();
while(reader.ready()){
sb.append((char)reader.read());
}
5、关闭读入数据流:reader.close();
6、关闭文件输入字符流:fip.close();
try{ //系统输出数据到文件 String str = new String("中文输入!"); File f = new File("D:/a.txt"); OutputStream output = new FileOutputStream(f); OutputStreamWriter write = new OutputStreamWriter(output,"utf-8"); write.append(str); write.append("\r\n"); write.append("English"); write.close(); output.close(); //文件输入数据到系统 FileInputStream fip = new FileInputStream(f); InputStreamReader reader = new InputStreamReader(fip,"utf-8"); StringBuffer sb = new StringBuffer(); while(reader.ready()){ sb.append((char)reader.read()); } reader.close(); fip.close(); System.out.println(sb); }catch(IOException e){ e.printStackTrace(); }
时间: 2024-10-12 15:55:33