共計 1083 個字符,預計需要花費 3 分鐘才能閱讀完成。
Java 中可以使用文件輸入流(FileInputStream)和文件輸出流(FileOutputStream)來讀取和輸出文件流。
讀取文件流的步驟如下:
- 創建一個 File 對象,表示要讀取的文件。
- 創建一個 FileInputStream 對象,將 File 對象作為參數傳入。
- 創建一個 byte 數組,用于存儲從文件中讀取的數據。
- 調用 FileInputStream 對象的 read 方法,將數據讀取到 byte 數組中。
- 關閉 FileInputStream 對象。
示例代碼如下:
import java.io.*;
public class FileReadExample {public static void main(String[] args) {
try {File file = new File("path/to/file.txt");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
String content = new String(data, "UTF-8");
System.out.println(content);
} catch (IOException e) {e.printStackTrace();
}
}
}
輸出文件流的步驟如下:
- 創建一個 File 對象,表示要輸出的文件。
- 創建一個 FileOutputStream 對象,將 File 對象作為參數傳入。
- 將要輸出的數據寫入到 FileOutputStream 對象中。
- 關閉 FileOutputStream 對象。
示例代碼如下:
import java.io.*;
public class FileWriteExample {public static void main(String[] args) {
try {File file = new File("path/to/file.txt");
FileOutputStream fos = new FileOutputStream(file);
String content = "This is the content to be written to the file.";
byte[] data = content.getBytes("UTF-8");
fos.write(data);
fos.close();
System.out.println("File written successfully.");
} catch (IOException e) {e.printStackTrace();
}
}
}
丸趣 TV 網 – 提供最優質的資源集合!
正文完
發表至: Java
2023-12-20