在 Java 中,可以使用 System.getProperty('user.home') 方法获取当前用户的主文件夹路径,然后将文件写入该路径下的 D:\file 文件夹中。以下是实现的示例代码:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {
    public static void main(String[] args) {
        String userHome = System.getProperty("user.home");
        String filePath = userHome + File.separator + "D:\file" + File.separator + "example.txt";

        try {
            FileWriter writer = new FileWriter(filePath);
            writer.write("Hello, World!");
            writer.close();
            System.out.println("File written successfully.");
        } catch (IOException e) {
            System.out.println("An error occurred while writing the file.");
            e.printStackTrace();
        }
    }
}

在上面的示例中,System.getProperty('user.home') 方法获取当前用户的主文件夹路径,然后使用 File.separator 来保证跨平台的路径分隔符。最后,通过 FileWriter 来写入文件。请注意,如果 D:\file 文件夹不存在,需要先创建该文件夹。

Java 写文件到用户本地文件夹 D:\file

原文地址: https://www.cveoy.top/t/topic/qgVr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录