分别使用(字符流)和(字节流)对文件进行读写操作

来源:互联网 发布:seo每日工作 编辑:程序博客网 时间:2024/05/27 12:22
一.使用(字符流)对文件进行读写操作
/* * 使用字符流对文件进行读写操作 */import java.io.BufferedReader;import java.io.FileInputStream;import java.io.InputStreamReader;import java.io.PrintWriter;public class T04 {public static void main(String[] args) throws Exception{String value = "中国风\n";String value2 = "a中国风\n";// 向文件中写入内容PrintWriter pw = new PrintWriter("temp.txt","UTF-8");pw.write(value);pw.write(value2);pw.close();// 从文件中读取内容BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("temp.txt"),"utf-8"));String b;while((b = br.readLine())!=null){// 按行读取System.out.println(b);}br.close();}}
运行结果:
中国风a中国风
二.使用(字节流)对文件进行读写操作
/* * 使用字节流对文件进行读写操作 */import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.File;public class T05 {public static void main(String[] args) throws Exception{String value = "中国风\n";String value2 = "a中国风\n";// 向文件中写入内容File f = new File("temp.txt");FileOutputStream fos = new FileOutputStream(f);fos.write(value.getBytes("UTF-8"));// 可以指定编码fos.write(value2.getBytes());fos.close();// 从文件中读取内容FileInputStream fis = new FileInputStream(f);byte b[] = new byte[(int)f.length()];int len = fis.read(b);// 读取后返回长度fis.close();System.out.println(new String(b));}}
运行结果:
涓浗椋�a中国风



原创粉丝点击