代碼如下:
package javalean;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileTest {
public FileTest() {
}
public static void main(String[] args) {
FileAppendDemo();
};
public static void FileAppendDemo() {
String path = "E:\\apks\\my.txt";
// java文件輸出流
FileOutputStream fos = null;
// File對象代表磁盤中實際存在的文件和目錄
File file = new File(path);
try {
if (!file.exists()) {
// 在文件系統中根據保存在文件中的路徑信息,創建一個新的空文件。如果創建成功就會返回true,如果文件存在返回false。注意:如果他已經存在但不是文件,可能是目錄也會返回false。
boolean hasFile = file.createNewFile();
if (!hasFile) {
fos = new FileOutputStream(file);
}
} else {
// 以追加的方式創建一個文件輸出流
fos = new FileOutputStream(file, true);
}
fos.write("test".getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
參考資料:
1.public boolean createNewFile () 解釋
Creates a new, empty file on the file system according to the path information stored in this file. This method returns true if it creates a file, false if the file already existed. Note that it returns false even if the file is not a file (because it's a directory, say).
在文件系統中根據保存在文件中的路徑信息,創建一個新的空文件。如果創建成功就會返回true,如果文件存在返回false。注意:如果他已經存在但不是文件,可能是目錄也會返回false。
2.file.createNewFile()有實際意義嗎?
https://ask.csdn.net/questions/382747
雖然我沒有看過FileOutputStream這個類的源代碼,但是我估計里面也是掉用了這個方法,有的時候你不使用流,但是也要在某個地方創建文件不就用到了嗎,再說流是有開銷的,你使用完了還要關,而且根據程序設計原則就是把不同功能的模塊區分出來,文件類專門管理文件,文件流專門負責傳輸文件,這是語言設計,就像高級流關閉之后,包含的低級流也會自動關閉,但是還不是有關閉的方法,你說有什么意義呢
