任何人都知道为什么下面的代码不会在C:目录中创建新文件?
public class FirstFileProgram {
import java.io.* ;
public static void main(String[] args) {
File f=new File("C:\\text.txt");
System.out.println(f.getName());
System.out.println(f.exists());
}
答案 0 :(得分:0)
您已创建一个链接到C:\ text.txt文件的对象,但实际上并未创建文件。您需要使用createNewFile()来创建使用文件类对象即f的文件。见下文:
public class FirstFileProgram { public static void main(String [] args){
File f = null;
boolean bool = false;
try {
// create new file
f = new File("test.txt");
// tries to create new file in the system
bool = f.createNewFile();
// prints
System.out.println("File created: "+bool);
// deletes file from the system
f.delete();
// delete() is invoked
System.out.println("delete() method is invoked");
// tries to create new file in the system
bool = f.createNewFile();
// print
System.out.println("File created: "+bool);
}catch(Exception e){
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
@Alok Gupta答案还可以。只是因为您使用的是Java 7或更高版本,您可以使用
public class CreateFileUsingJava {
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\test.txt");
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("File exists: " + e.getMessage());
}
}
}