gpt4 book ai didi

java 如何在同名目录中创建.txt

转载 作者:行者123 更新时间:2023-12-02 09:08:37 24 4
gpt4 key购买 nike

所以我需要创建一个目录并在该目录中创建一个同名的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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com