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

标签 java directory

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

相关文章:

javascript - 我如何使用 javascript 文件夹对象

c - stat()不适用于父目录

java - 如何以相同的顺序将二维数组中的元素转移到一维数组中?

java - 为什么服务器端套接字在读取 "\n.\n"后没有收到消息

iphone - iOS 中可用的路径目录

directory - 在 Mathematica 中指定保存目录

java - 如何在不遵循符号链接(symbolic link)的情况下递归删除文件夹?

java - 什么是NullPointerException,我该如何解决?

java - 需要配置Spring Security和Hibernate

java - cassandra db 慢速连接