標籤:構建 public 檔案寫入 pack 建立 fileinput pre stat 檔案的
//構造檔案File類
File f=new File(fileName);
//判斷是否為目錄
f.isDirectory();
//擷取目錄下的檔案名稱
String[] fileName=f.list();
//擷取目錄下的檔案
File[] files=f.listFiles();
1、Java怎麼讀取檔案
package com.yyb.file; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; /* * 讀取檔案: * 1、找到指定的檔案 * 2、根據檔案建立檔案的輸入資料流 * 3、建立位元組數組 * 4、讀取內容,放到位元組數組裡面 * 5、關閉輸入資料流 */ public class FileRead { public static void main(String[] args) { // 構建指定檔案 File file = new File("E:" + File.separator + "hello.txt"); InputStream in = null; try { // 根據檔案建立檔案的輸入資料流 in = new FileInputStream(file); // 建立位元組數組 byte[] data = new byte[1024]; // 讀取內容,放到位元組數組裡面 in.read(data); System.out.println(new String(data)); } catch (Exception e) { e.printStackTrace(); } finally { try { // 關閉輸入資料流 in.close(); } catch (Exception e) { e.printStackTrace(); } } } } 2、Java怎麼寫入檔案
package com.yyb.file; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; /* * 寫入檔案: * 1、找到指定的檔案 * 2、根據檔案建立檔案的輸出資料流 * 3、把內容轉換成位元組數組 * 4、向檔案寫入內容 * 5、關閉輸入資料流 */ public class FileWriter { public static void main(String[] args) { // 構建指定檔案 File file = new File("E:" + File.separator + "hello.txt"); OutputStream out = null; try { // 根據檔案建立檔案的輸出資料流 out = new FileOutputStream(file); String message = "我是好人。"; // 把內容轉換成位元組數組 byte[] data = message.getBytes(); // 向檔案寫入內容 out.write(data); } catch (Exception e) { e.printStackTrace(); } finally { try { // 關閉輸出資料流 out.close(); } catch (Exception e) { e.printStackTrace(); } } } } 3、Java怎麼複製檔案
<span style="font-size:18px;">package com.yyb.file; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; /* * 實現思路: * 1、構建源檔案與目標檔案 * 2、源檔案建立輸入資料流,目標檔案建立輸出資料流 * 3、建立位元組數組 * 4、使用迴圈,源檔案讀取一部分內容,目標檔案寫入一部分內容,直到寫完所有內容 * 5、關閉源檔案輸入資料流,目標檔案輸出資料流 */ public class FileCopy { public static void main(String[] args) { // 構建源檔案 File file = new File("E:" + File.separator + "HelloWorld.txt"); // 構建目標檔案 File fileCopy = new File("D:" + File.separator + "HelloWorld"); InputStream in = null; OutputStream out = null; try { // 目標檔案不存在就建立 if (!(fileCopy.exists())) { fileCopy.createNewFile(); } // 源檔案建立輸入資料流 in = new FileInputStream(file); // 目標檔案建立輸出資料流 out = new FileOutputStream(fileCopy, true); // 建立位元組數組 byte[] temp = new byte[1024]; int length = 0; // 源檔案讀取一部分內容 while ((length = in.read(temp)) != -1) { // 目標檔案寫入一部分內容 out.write(temp, 0, length); } } catch (Exception e) { e.printStackTrace(); } finally { try { // 關閉檔案輸入輸出資料流 in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } } } }</span><span style="font-size: 24px;"> </span>
Java中IO流檔案讀取、寫入和複製