我正在尝试在 java 中创建 createNewFile()。我已经记下了以下示例。我已经编译了它,但遇到了运行时错误。
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();
}
}
编译正常。我得到的运行时错误是
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)
最佳答案
这里有几点
1- 正如 Victor 所说,您缺少前导斜线
2- 如果您的文件已创建,则每次调用此方法“File.createNewFile()”时都会返回 false
3- 您的类非常依赖于平台(Java 是强大的编程语言的主要原因之一是它不依赖于平台),相反您可以使用 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
关于java - Java 中的 File.createNewFile() 失败(Ubuntu 12.04),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18807427/