java 列印流與commons-IO
阿新 • • 發佈:2020-08-07
一 列印流
1.列印流的概述
列印流新增輸出資料的功能,使它們能夠方便地列印各種資料值表示形式.
列印流根據流的分類:
位元組列印流 PrintStream
字元列印流 PrintWriter
方法:
void print(String str): 輸出任意型別的資料,
void println(String str): 輸出任意型別的資料,自動寫入換行操作
程式碼演示:
/* * 需求:把指定的資料,寫入到printFile.txt檔案中 * * 分析: * 1,建立流 * 2,寫資料 * 3,關閉流 */ public classPrintWriterDemo { public static void main(String[] args) throws IOException { //建立流 //PrintWriter out = new PrintWriter(new FileWriter("printFile.txt")); PrintWriter out = new PrintWriter("printFile.txt"); //2,寫資料 for (int i=0; i<5; i++) { out.println("helloWorld"); } //3,關閉流 out.close(); } }
2.列印流完成資料自動重新整理
可以通過構造方法,完成檔案資料的自動重新整理功能
構造方法:
開啟檔案自動重新整理寫入功能
public PrintWriter(OutputStream out, boolean autoFlush)
public PrintWriter(Writer out, boolean autoFlush)
程式碼演示:
/* * 分析: * 1,建立流 * 2,寫資料 */ public classPrintWriterDemo2 { public static void main(String[] args) throws IOException { //建立流 PrintWriter out = new PrintWriter(new FileWriter("printFile.txt"), true); //2,寫資料 for (int i=0; i<5; i++) { out.println("helloWorld"); } //3,關閉流 out.close(); } }
二commons-IO
1.FileUtils
提供檔案操作(移動檔案,讀取檔案,檢查檔案是否存在等等)的方法。
常用方法:
readFileToString(File file):讀取檔案內容,並返回一個String;
writeStringToFile(File file,String content):將內容content寫入到file中;
copyDirectoryToDirectory(File srcDir,File destDir);資料夾複製
copyFile(File srcFile,File destFile);檔案複製
程式碼演示:
/* * 完成檔案的複製 */ public class CommonsIODemo01 { public static void main(String[] args) throws IOException { //method1("D:\\test.avi", "D:\\copy.avi"); //通過Commons-IO完成了檔案複製的功能 FileUtils.copyFile(new File("D:\\test.avi"), new File("D:\\copy.avi")); } //檔案的複製 private static void method1(String src, String dest) throws IOException { //1,指定資料來源 BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); //2,指定目的地 BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); //3,讀 byte[] buffer = new byte[1024]; int len = -1; while ( (len = in.read(buffer)) != -1) { //4,寫 out.write(buffer, 0, len); } //5,關閉流 in.close(); out.close(); } } /* * 完成檔案、資料夾的複製 */ public class CommonsIODemo02 { public static void main(String[] args) throws IOException { //通過Commons-IO完成了檔案複製的功能 FileUtils.copyFile(new File("D:\\test.avi"), new File("D:\\copy.avi")); //通過Commons-IO完成了資料夾複製的功能 //D:\基礎班 複製到 C:\\abc資料夾下 FileUtils.copyDirectoryToDirectory(new File("D:\\基礎班"), new File("C:\\abc")); } }