1、输出流的三种方式
1)按字符输出,覆盖原来的内容
2)按字节输出,覆盖原来的内容
3)不覆盖原来的内容
package output; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; public class OutPutTest { public static void main(String[] args) { File file = new File("C:\\Users\\Administrator\\Desktop\\zzz.txt"); // characterWriter(file, "ABC"); // byteWriter(file, "ABC"); characterWriter2(file, "123"); } /* * 1、按字符输出,输出的内容直接覆盖以前的文本 */ public static void characterWriter(File file, String count) { BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new PrintWriter(file)); bufferedWriter.write(count); bufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } /* * 2、按字节输出,覆盖原来内容 */ public static void byteWriter(File file, String count) { OutputStream outputStream = null; try { outputStream = new FileOutputStream(file); outputStream.write(count.getBytes()); outputStream.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } /* * 3、输出的内容不覆盖以前的内容 */ public static void characterWriter2(File file, String count) { BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new FileWriter(file, true)); bufferedWriter.write(count); bufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
时间: 2024-11-13 10:08:57