所以我需要创建一个目录并在该目录中创建一个同名的txt文件.. 假设我的类(class)名称是“Mike”
需要进行以下操作
->迈克(目录)
---->迈克.txt
这是我的代码:
//variable className is the name of the current class
//create directory using the name of the class
File Dirfile = new File("F:\\"+ className );
Dirfile.mkdir();
//create the .txt inside the dir using the name of the class
FileWriter fw = new FileWriter("F:\\" + Dirfile + className + ".txt", true);//<-- this code is not correct.. but i need something like this i mentioned before
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
最佳答案
如果FileWriter
不是必要条件,您可以尝试使用以下代码。
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test1 {
public static void main(String[] args) throws IOException {
String className = "Mike";
File Dirfile = new File("F:\\" + className + File.separator + className + ".txt");
Dirfile.getParentFile().mkdirs();
Dirfile.createNewFile();
Path path = Paths.get(Dirfile.getAbsolutePath());
Files.write(path, "some test content...".getBytes());
}
}
关于java 如何在同名目录中创建.txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59591176/