Java - 创建新文件
时间:2020-02-23 14:34:58 来源:igfitidea点击:
有很多方法可以在Java中创建文件。
创建文件是一项非常简单的任务。
我们将学习5种不同的方法来创建文件。
使用java.io.file类的createNewFile方法
这是创建文件的最简单和最古老的方式。
它是简单的快照,用于在Java中创建文件。
package org.igi.theitroad;
import java.io.File;
import java.io.IOException;
public class CreateFileMain {
public static void main(String[] args) {
try {
File file = new File("c://newtheitroadfile.txt");
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用JDK 7的java.nio.file.files
这是在我将房上的JDK 7之后创建文件的首选方法。
请注意,在已经存在的情况下,它将抛出FileAlreadyXistsexception。
package org.igi.theitroad;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFileMain {
public static void main(String[] args) {
Path newFilePath = Paths.get("C://newtheitroadFile_jdk7.txt");
try {
Files.createFile(newFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用java.io.fileOutputStream.
我们可以使用FileOutputStream的Write方法创建新文件并将内容写入它。
package org.igi.theitroad;
import java.io.FileOutputStream;
import java.io.IOException;
public class CreateFileMain {
public static void main(String[] args) throws IOException {
String data = "Java writing to file";
FileOutputStream out = new FileOutputStream("c://testtheitroad.txt");
out.write(data.getBytes());
out.close();
}
}
使用guava库
以下是使用以下Oneliner创建文件的简单方法。
Files.touch(new File("c://newtheitroadFile_guava.txt"));
使用通用IO库
以下是使用公共IO库创建新文件的另一种方法。
请注意,如果档案alleay存在,它没有任何作用。
它类似于Linux中的触摸命令。
Files.touch(new File("c://newtheitroadFile_commonUtil.txt"));

