0
Follow
0
View

Question about #java# : Create folder without detecting no folder, create txt file directly after creating, and then write content in txt file

duhuafeng2006 注册会员
2023-02-26 19:04

The following answers are quoted from GPT-3 model, please use them wisely:

示例

可以使用Java的File类来检测文件夹是否存在,如果不存在则新建一个文件夹: 

// 定义文件夹路径 
String folderPath = "PATH_TO_FOLDER"; 

// 创建文件夹对象 
File folder = new File(folderPath); 

// 判断文件夹是否存在,如果不存在则创建一个新文件夹 
if (!folder.exists()) { 
    folder.mkdirs(); 
} 

// 创建txt文件
String filePath = folderPath + "/file.txt"; 
File file = new File(filePath); 

// 向文件写入内容 
try { 
    FileWriter fw = new FileWriter(file); 
    BufferedWriter bw = new BufferedWriter(fw); 

    // 写入文件 
    bw.write("The content goes here"); 

    bw.close(); 
    fw.close(); 
} catch (IOException e) { 
    e.printStackTrace(); 
}

Please accept my answer if it answers your question

cts3003 注册会员
2023-02-26 19:04

code

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class JustTest {
    public static void main(String[] args) {
        String path = "/tmp/test";
        String fileName = "test.txt";
        File dir = new File(path);
        // mkdirs 方法会判断路径是否存在,如果存在直接返回,不存在会去创建这个路径
        dir.mkdirs();

        File file = new File(path + "/" + fileName);

        // 通过文件流写入
        try (FileWriter fw = new FileWriter(file);
             BufferedWriter bw = new BufferedWriter(fw)) {
            // 写入文件
            bw.write("The content goes here");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}