java 文件输出流_Java 文件输出流
Java IO教程 - Java文件輸出流
創(chuàng)建輸出流
要寫入文件,我們需要?jiǎng)?chuàng)建一個(gè)FileOutputStream類的對(duì)象,它將表示輸出流。// Create a file output stream
String destFile = "test.txt";
FileOutputStream fos = new FileOutputStream(destFile);
當(dāng)寫入文件時(shí),如果文件不存在,Java會(huì)嘗試創(chuàng)建文件。我們必須準(zhǔn)備好處理這個(gè)異常,將代碼放在try-catch塊中,如下所示:try {
FileOutputStream fos = new FileOutputStream(srcFile);
}catch (FileNotFoundException e){
// Error handling code goes here
}
如果文件包含數(shù)據(jù),數(shù)據(jù)將被擦除。為了保留現(xiàn)有數(shù)據(jù)并將新數(shù)據(jù)附加到文件,我們需要使用FileOutputStream類的另一個(gè)構(gòu)造函數(shù),它接受一個(gè)布爾標(biāo)志,用于將新數(shù)據(jù)附加到文件。
要將數(shù)據(jù)附加到文件,請(qǐng)?jiān)诘诙€(gè)參數(shù)中傳遞true,使用以下代碼。FileOutputStream fos = new FileOutputStream(destFile, true);
寫數(shù)據(jù)
FileOutputStream類有一個(gè)重載的write()方法將數(shù)據(jù)寫入文件。我們可以使用不同版本的方法一次寫入一個(gè)字節(jié)或多個(gè)字節(jié)。
通常,我們使用FileOutputStream寫入二進(jìn)制數(shù)據(jù)。
要向輸出流中寫入諸如“Hello"的字符串,請(qǐng)將字符串轉(zhuǎn)換為字節(jié)。
String類有一個(gè)getBytes()方法,該方法返回表示字符串的字節(jié)數(shù)組。我們給FileOutputStream寫一個(gè)字符串如下:String text = "Hello";
byte[] textBytes = text.getBytes();
fos.write(textBytes);
要插入一個(gè)新行,使用line.separator系統(tǒng)變量如下。String lineSeparator = System.getProperty("line.separator");
fos.write(lineSeparator.getBytes());
我們需要使用flush()方法刷新輸出流。fos.flush();
刷新輸出流指示如果任何寫入的字節(jié)被緩沖,則它們可以被寫入數(shù)據(jù)宿。
關(guān)閉輸出流類似于關(guān)閉輸入流。我們需要使用close()方法關(guān)閉輸出流。// Close the output stream
fos.close();
close()方法可能拋出一個(gè)IOException異常。如果我們希望自動(dòng)關(guān)閉tit,請(qǐng)使用try-with-resources創(chuàng)建輸出流。
以下代碼顯示如何將字節(jié)寫入文件輸出流。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();
}
}
}
上面的代碼生成以下結(jié)果。
總結(jié)
以上是生活随笔為你收集整理的java 文件输出流_Java 文件输出流的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux 内核编程之proc虚拟文件系
- 下一篇: 01.Matlab文件类型