标签:ati hello pre ace sharp pac todo 写入 txt
FileOutputStream如果不理解可以查看API描述
这里不再介绍
package cn.bean.demo.inoutstream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; public class FileOutPutStreamTest { public static void main(String[] args) { testReadWrite(); } static void testReadWrite() { // 获从输入流,读取目标资源信息 try (InputStream in = new FileInputStream("String1.txt"); OutputStream out = new FileOutputStream("String2.txt")) { //每次读取的内容放入到一个缓冲区 byte[] b=new byte[20]; //每次放入到缓冲区的字节个数 int len=0; while((len=in.read(b))!=-1){ out.write(b, 0, len); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
OutputStreamWriter和FileWriter 的用法[OutputStreamWriter可以用来读取中文和写入中文,但是要保证写入的目标创建的文件也是utf8,系统的编码和项目中的编码,如果项目是GBK,创建和输出后也会是乱码]
package cn.bean.demo.readwrite; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; public class WreteTest { public static void main(String[] args) { //testReadWrite(); testOutputStreamWriter(); } static void testReadWrite() { try (Reader reader = new FileReader("String1.txt"); Writer writer = new FileWriter("String2.txt");) { // 创建每次读取数据的缓冲区,可以想象成水桶 char[] c = new char[19]; // 每次装入缓冲区的字节个数 int len = 0; while ((len = reader.read(c)) != -1) { // 把每次装入桶中的内容写入到文件中,每次写入0到len,因为len是每次读取到的实际内容个数 writer.write(c, 0, len); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } static void testOutputStreamWriter() { try (InputStream in = new FileInputStream("hello.txt"); Reader read = new InputStreamReader(in, "utf-8"); OutputStream out = new FileOutputStream("hell22.txt"); Writer writer = new OutputStreamWriter(out, "utf-8");) { //创建缓冲区用来存放每次读取的数据 char[] ch=new char[50]; //每次放入到缓冲区的数据的实际个数 int len=0; String content=""; while((len=read.read(ch))!=-1){
// 这样也可以 writer.write(ch, 0, len); content+=new String(ch,0,len); } writer.write(content); System.out.println(content); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
标签:ati hello pre ace sharp pac todo 写入 txt
原文地址:http://www.cnblogs.com/sunjiqiang/p/6079537.html