package demo.test2;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
public class PriterWriterDemoAll {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException{
p1();
p2();
p3();
p4();
p5();
}
/**
* 使用FileOutputStream 字节流输出
* ==============使用FileOutputStream 是否追加内容
* @throws FileNotFoundException
*/
public static void p1() throws FileNotFoundException {
FileOutputStream fos = new FileOutputStream("a11.txt",true);
PrintWriter pw = new PrintWriter(fos);
pw.println("1234567");
pw.append("1234567");
pw.close();
}
/**
* 使用PrintWriter 字符流
* 直接使用PrintWriter 类可以指定字符集
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static void p2() throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter pw = new PrintWriter("pw.txt", "utf-8");
pw.println("123456");
pw.println("hello world");
pw.append("ddd");
pw.close();
}
/**
* 使用字符缓冲流输入数据
* BufferedWriter bf = new BufferedWriter(new PrintWriter(new FileOutputStream("a33.txt",true)));
* @throws IOException
*/
public static void p3() throws IOException{
FileOutputStream fos = new FileOutputStream("a33.txt",true);
PrintWriter pw = new PrintWriter(fos);
BufferedWriter bf = new BufferedWriter(pw);
bf.newLine(); //创建新 的一行
bf.append("你好 L BufferedWriter");
bf.close();
}
/**
* 使用FileOutputStream 字节流 与 OutputStreamWriter 字符流搭配将内容写入文件
* 简写OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("a.txt",true), "gbk");
* @throws IOException
*/
public static void p4() throws IOException{
FileOutputStream fis = new FileOutputStream("a.txt",true);
OutputStreamWriter osw = new OutputStreamWriter(fis, "gbk");
osw.append("java\\n\\n");
osw.write("hello world");
osw.close();
}
/**
* 字符集格式转换
* 需要用到 OutputStreamWriter 与 InputStreamReader 两个类
* 使用UTF-8编码将每一个字符读取出来,再以GBK编码将字符写入另一个文件即可
* @throws IOException
*/
public static void p5() throws IOException{
FileInputStream fis = new FileInputStream("a11.txt");
InputStreamReader isr = new InputStreamReader(fis, "utf-8");
FileOutputStream fos = new FileOutputStream("a11_copy.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
char[] ch = new char[1024*5];
int len = -1;
while((len =isr.read(ch)) != -1){
osw.write(ch, 0,len);
}
//关闭流
isr.close();
osw.close();
}
}
File操作(6)------------------- printWriter,bufferedWriter
最新推荐文章于 2023-11-14 08:57:51 发布