![](/img/trans.png)
[英]Java file.createNewFile() returns false though the file is created
[英]File.createNewFile() failing in java (Ubuntu 12.04)
我正在嘗試在java中創建newFile()。我寫下了以下示例。我已經編譯了它,但是遇到運行時錯誤。
import java.io.File;
import java.io.IOException;
public class CreateFileExample
{
public static void main(String [] args)
{
try
{
File file = new File("home/karthik/newfile.txt");
if(file.createNewFile())
{
System.out.println("created new fle");
}else
{
System.out.println("could not create a new file");
}
}catch(IOException e )
{
e.printStackTrace();
}
}
}
它正在編譯OK。我得到的運行時錯誤是
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:947)
at CreateFileExample.main(CreateFileExample.java:16)
您在文件路徑中缺少前導斜杠。
嘗試這個:
File file = new File("/home/karthik/newfile.txt");
那應該工作!
這里有幾點
1-正如維克多(Victor)所說的,您錯過了領先的斜杠
2-如果已創建文件,則每次調用此方法“ File.createNewFile()”都將返回false
3-您的類非常依賴平台(Java是強大的編程語言的主要原因之一是它依賴於NON-PLATFORM),而是可以使用System.getProperties()檢測相對位置拋出:
// get System properties :
java.util.Properties properties = System.getProperties();
// to print all the keys in the properties map <for testing>
properties.list(System.out);
// get Operating System home directory
String home = properties.get("user.home").toString();
// get Operating System separator
String separator = properties.get("file.separator").toString();
// your directory name
String directoryName = "karthik";
// your file name
String fileName = "newfile.txt";
// create your directory Object (wont harm if it is already there ...
// just an additional object on the heap that will cost you some bytes
File dir = new File(home+separator+directoryName);
// create a new directory, will do nothing if directory exists
dir.mkdir();
// create your file Object
File file = new File(dir,fileName);
// the rest of your code
try {
if (file.createNewFile()) {
System.out.println("created new fle");
} else {
System.out.println("could not create a new file");
}
} catch (IOException e) {
e.printStackTrace();
}
這樣,您將在任何平台上的任何主目錄中創建文件,該文件適用於我的Windows操作系統,並且預期也適用於Linux或Ubuntu
實際上,當如上例中沒有目錄“ karthik”時,就會出現此錯誤,並且createNewFile()僅用於創建文件,而不是用於目錄,將mkdir()用於目錄,然后將createNewFile()用於文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.