[Java] Create File with java.io.File class

时间:2023-03-09 14:29:15
[Java] Create File with java.io.File class

Create a file with some content in some specific location. The reference is here.

 /**
* Write fileContent in a file and save it into FileToCreatePath
*
* @param fileContent content of the file
* @param FileToCreatePath path of the file been saved
* @throws IOException
*/
private static void createFile(String fileContent, Path FileToCreatePath) throws IOException
{
File file = FileToCreatePath.toFile();
if (file.createNewFile())
{
System.out.println(FileToCreatePath.toString() + " is created!");
}
else
{
System.out.println(FileToCreatePath.toString() + " already exists.");
}
FileWriter writer = new FileWriter(file);
writer.write(fileContent);
writer.close();
}

E.g  if want to create a HelloWorld.txt file, then we just need to use

static final String _txtContent = "Hello World!!!";
static final Path _FilePath = Paths.get(
System.getenv("APPDATA"),
"HelloWorld.txt"
); // if we want to create different file , like .java, .py or .vbs, we just need to change the name in the _FilePath. createFile(_txtContent, _FilePath);