How does file creation work in Java

丶灬走出姿态 提交于 2019-12-10 18:52:18

问题


I am trying to create a file using

File newFile = new File("myFile");

However no file called "myFile" is created. This is within a Web application Project i.e. proper form to be pakaged as a WAR but I am calling it as part of a main method (just to see how this works).

How can I make it so that a new file is created at a location relative to the current one i.e not have to put in an absolute path.

EDIT:

newFile.createFile();

Doesn't seem to work:

Here is the entire code:

import java.io.File;
import java.io.IOException;

public class Tester {

public static void main(String[] args) throws IOException{
    Tester test = new Tester();
    test.makeFile();
}

public void makeFile() throws IOException{
    File newFile = new File("myFile");
    newFile.createNewFile();
    }
}

回答1:


In answer to your comment. The file will be created in the current directory of the process, unless you specifiy otherwise.

// new file in current directory
File f = new File("yourFile");
f.createNewFile();
System.out.println("Path:" + f.getAbsolutePath());

To create it in a directory of your choosing:

File f = new File("c:\\yourDirectory","yourFile");
f.createNewFile();
System.out.println("Path:" + f.getAbsolutePath());



回答2:


newFile.createNewFile();




回答3:


you could use newFile.createNewFile();



来源:https://stackoverflow.com/questions/2452738/how-does-file-creation-work-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!