Java指定路径文件的自动创建及写入

Java指定路径文件的自动创建及写入

一直写JavaWeb项目为多,一些基础java代码写法反而容易忘记,最近写到的一个小程序需要输出至文件,多次找不到文件路径之后,想要写自动创建文件及路径的一个方法却想不起来。写好之后便想把它记录下来。

这个用法很简单,指定需要创建的文件夹路径以及文件名,若文件存在则不创建,若文件及路径不存在就会自动创建路径和文件,方便之后读写操作,而不用担心文件不存在(手工创建打错等等= =)。


public class DemoOutputToTxt {
    public static final String FILE_NAME = "Output.txt";//要创建的文件名
    public static final String FILE_PATH = "e:/OrderSplit/";//文件指定存放的路径

    public static void creatFile(String filePath, String fileName) {
        File folder = new File(filePath);
        //文件夹路径不存在
        if (!folder.exists() && !folder.isDirectory()) {
            System.out.println("文件夹路径不存在,创建路径:" + filePath);
            folder.mkdirs();
        } else {
            System.out.println("文件夹路径存在:" + filePath);
        }

        // 如果文件不存在就创建
        File file = new File(filePath + fileName);
        if (!file.exists()) {
            System.out.println("文件不存在,创建文件:" + filePath + fileName);
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("文件已存在,文件为:" + filePath + fileName);
        }
    }

public static void main(String[] args) throws FileNotFoundException {
        FileOutputStream outFile = null;

        try {
            creatFile(FILE_PATH, FILE_NAME);
            outFile = new FileOutputStream(FILE_PATH + FILE_NAME);
            ......//后续文件操作
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

十分简单的一段,留作之后自己查看吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值