java 文件输出流_Java 文件输出流
Java IO教程 - Java文件輸出流
創建輸出流
要寫入文件,我們需要創建一個FileOutputStream類的對象,它將表示輸出流。// Create a file output stream
String destFile = "test.txt";
FileOutputStream fos = new FileOutputStream(destFile);
當寫入文件時,如果文件不存在,Java會嘗試創建文件。我們必須準備好處理這個異常,將代碼放在try-catch塊中,如下所示:try {
FileOutputStream fos = new FileOutputStream(srcFile);
}catch (FileNotFoundException e){
// Error handling code goes here
}
如果文件包含數據,數據將被擦除。為了保留現有數據并將新數據附加到文件,我們需要使用FileOutputStream類的另一個構造函數,它接受一個布爾標志,用于將新數據附加到文件。
要將數據附加到文件,請在第二個參數中傳遞true,使用以下代碼。FileOutputStream fos = new FileOutputStream(destFile, true);
寫數據
FileOutputStream類有一個重載的write()方法將數據寫入文件。我們可以使用不同版本的方法一次寫入一個字節或多個字節。
通常,我們使用FileOutputStream寫入二進制數據。
要向輸出流中寫入諸如“Hello"的字符串,請將字符串轉換為字節。
String類有一個getBytes()方法,該方法返回表示字符串的字節數組。我們給FileOutputStream寫一個字符串如下:String text = "Hello";
byte[] textBytes = text.getBytes();
fos.write(textBytes);
要插入一個新行,使用line.separator系統變量如下。String lineSeparator = System.getProperty("line.separator");
fos.write(lineSeparator.getBytes());
我們需要使用flush()方法刷新輸出流。fos.flush();
刷新輸出流指示如果任何寫入的字節被緩沖,則它們可以被寫入數據宿。
關閉輸出流類似于關閉輸入流。我們需要使用close()方法關閉輸出流。// Close the output stream
fos.close();
close()方法可能拋出一個IOException異常。如果我們希望自動關閉tit,請使用try-with-resources創建輸出流。
以下代碼顯示如何將字節寫入文件輸出流。import java.io.File;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) {
String destFile = "luci2.txt";
// Get the line separator for the current platform String lineSeparator = System.getProperty("line.separator");
String line1 = "test";
String line2 = "test1";
String line3 = "test2";
String line4 = "test3";
try (FileOutputStream fos = new FileOutputStream(destFile)) {
fos.write(line1.getBytes());
fos.write(lineSeparator.getBytes());
fos.write(line2.getBytes());
fos.write(lineSeparator.getBytes());
fos.write(line3.getBytes());
fos.write(lineSeparator.getBytes());
fos.write(line4.getBytes());
// Flush the written bytes to the file fos.flush();
System.out.println("Text has been written to "
+ (new File(destFile)).getAbsolutePath());
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
上面的代碼生成以下結果。
總結
以上是生活随笔為你收集整理的java 文件输出流_Java 文件输出流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux 内核编程之proc虚拟文件系
- 下一篇: java 打印 模板_Java输入输出模