最好的方法是:
String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);
f.getParentFile().mkdirs();
f.createNewFile();
您需要在写入之前确保父目录存在。您可以通过 File#mkdirs()
执行此操作。
File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...
通过 Java 7,您可以使用 Path
、Paths
和 Files
:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFile {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp/foo/bar.txt");
Files.createDirectories(path.getParent());
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("already exists: " + e.getMessage());
}
}
}
利用:
File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();
请注意,我将 Windows 文件系统中路径的正斜杠更改为双反斜杠。这将在给定路径上创建一个空文件。
FileOutputStream
写入它时,createNewFile()
是不必要的。
String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这应该在目录中创建一个新文件
在指定路径中创建新文件
import java.io.File;
import java.io.IOException;
public class CreateNewFile {
public static void main(String[] args) {
try {
File file = new File("d:/sampleFile.txt");
if(file.createNewFile())
System.out.println("File creation successfull");
else
System.out.println("Error while creating File, file already exists in specified path");
}
catch(IOException io) {
io.printStackTrace();
}
}
}
程序输出:
文件创建成功
令人惊讶的是,许多答案都没有给出完整的工作代码。这里是:
public static void createFile(String fullPath) throws IOException {
File file = new File(fullPath);
file.getParentFile().mkdirs();
file.createNewFile();
}
public static void main(String [] args) throws Exception {
String path = "C:/donkey/bray.txt";
createFile(path);
}
要创建一个文件并在那里写一些字符串:
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write(""); // for empty file
bufferedWriter.close();
这适用于 Mac 和 PC。
使用 FileOutputStream 试试这个:
public class Main01{
public static void main(String[] args) throws FileNotFoundException{
FileOutputStream f = new FileOutputStream("file.txt");
PrintStream p = new PrintStream(f);
p.println("George.........");
p.println("Alain..........");
p.println("Gerard.........");
p.close();
f.close();
}
}
当您通过文件输出流写入文件时,将自动创建文件。但请确保创建了所有必要的目录(文件夹)。
String absolutePath = ...
try{
File file = new File(absolutePath);
file.mkdirs() ;
//all parent folders are created
//now the file will be created when you start writing to it via FileOutputStream.
}catch (Exception e){
System.out.println("Error : "+ e.getmessage());
}
不定期副业成功案例分享
new File("/a/b/test.txt")
对两个系统都有效。在 Windows 上,它将被写入与运行 JVM 的磁盘相同的磁盘。f.getParentFile().mkdirs(); f.createNewFile();