所以我一直在做最简单的事情。为Java应用程序创建文本文件。直接在C目录中:
File file = new File("C://function.txt");
System.out.println(file.exists());
文件永远不会出现,我更改了斜杠,更改了路径,没有任何内容。有人可以帮帮我吗?
答案 0 :(得分:3)
使用java创建新文件的方法有很多种:(首先应验证在该文件夹中创建文件的权限c:)
String path = "C:"+File.separator"function.txt";
File f = new File(path);
f.mkdirs();
f.createNewFile();
__或
try {
//What ever the file path is.
File f = new File("C:/function.txt");
FileOutputStream is = new FileOutputStream(f);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("Line 1!!");
w.close();
} catch (IOException e) {
System.err.println("Problem writing to the file function.txt");
}
答案 1 :(得分:3)
在Java 7之后,您应该使用new I/O API而不是File类来创建新文件。
以下是一个例子:
Path path = Paths.get("C://function.txt");
try {
Files.createFile(path);
System.out.println(Files.exists(path));
} catch (IOException e) {
e.printStackTrace();
}
答案 2 :(得分:2)
您只是创建一个File
对象,而不是文件本身。因此,为了创建新文件,您需要使用以下命令:
file .createNewFile();
这将在C:\
驱动器下创建您的文件。也许你也可以检查它是否已经存在并处理异常等。
答案 3 :(得分:1)
如果文件不存在,您可以创建一个新文件,如:
if(!file.exists()) {
try {
file.createNewFile();
System.out.println("Created a new File");
} catch (IOException e) {
e.printStackTrace();
}
}
答案 4 :(得分:1)
最简单的方法:
String path = "C:"+File.separator+"function.txt";
File file = new File(path);
System.out.println(file.exists());
答案 5 :(得分:1)
试试这个:
File file = new File("C://function.txt");
if (!file.isFile())
file.createNewFile();
答案 6 :(得分:1)
试试这个
File file = new File("C:/test.text");
f.createNewFile();