Ste*_*unn 178 java file-io file new-operator fileoutputstream
有没有办法以一种方式使用FileOutputStream,如果文件(String filename)不存在,那么它会创建它吗?
FileOutputStream oFile = new FileOutputStream("score.txt", false);
Run Code Online (Sandbox Code Playgroud)
tal*_*las 286
FileNotFoundException
如果文件不存在且无法创建(doc),它将抛出一个,但如果可以,它将创建它.为了确保在创建之前可能首先应该测试文件是否存在FileOutputStream
(createNewFile()
如果没有则创建,则为:)
File yourFile = new File("score.txt");
yourFile.createNewFile(); // if file already exists will do nothing
FileOutputStream oFile = new FileOutputStream(yourFile, false);
Run Code Online (Sandbox Code Playgroud)
Pet*_*rey 23
您可以创建一个空文件,无论它是否存在......
new FileOutputStream("score.txt", false).close();
Run Code Online (Sandbox Code Playgroud)
如果你想保留文件,如果它存在...
new FileOutputStream("score.txt", true).close();
Run Code Online (Sandbox Code Playgroud)
如果尝试在不存在的目录中创建文件,则只会获得FileNotFoundException.
Sha*_*dne 20
File f = new File("Test.txt");
if(!f.exists()){
f.createNewFile();
}else{
System.out.println("File already exists");
}
Run Code Online (Sandbox Code Playgroud)
将此传递f
给您的FileOutputStream
构造函数.
Nik*_*ahu 18
文件实用程序从Apache的百科全书是在一个单一的线,实现这样的好方法.
FileOutputStream s = FileUtils.openOutputStream(new File("/home/nikhil/somedir/file.txt"))
Run Code Online (Sandbox Code Playgroud)
这将创建父文件夹(如果不存在)并创建文件(如果不存在)并在文件对象是目录或无法写入时抛出异常.这相当于:
File file = new File("/home/nikhil/somedir/file.txt");
file.getParentFile().mkdirs(); // Will create parent directories if not exists
file.createNewFile();
FileOutputStream s = new FileOutputStream(file,false);
Run Code Online (Sandbox Code Playgroud)
如果不允许当前用户执行操作,则上述所有操作都将抛出异常.
如果不存在则创建文件。如果文件退出,清除其内容:
/**
* Create file if not exist.
*
* @param path For example: "D:\foo.xml"
*/
public static void createFile(String path) {
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
} else {
FileOutputStream writer = new FileOutputStream(path);
writer.write(("").getBytes());
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)