系统没有输出路径,创建目录的代码

import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStream;
import java.io.Writer;

public class Hello {

    public static void main(String[] args) throws Exception {
        
        //字符流 (输出流中含有中文时使用字符流) 
        charOutStream();

        //字节流
        byteOutStream();

}
    public static void charOutStream() throws Exception{
        // 1:利用File类找到要操作的对象
            File file = new File(path);//path指文件路径
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            
            //2:准备输出流
            Writer out = new FileWriter(file);
            out.write("测试字符流");
            out.close();
            
        }

    public static void byteOutStream() throws Exception {
        
        //1:使用File类创建一个要操作的文件路径
        File file = new File(path); //path指路径
        if(!file.getParentFile().exists()){ //如果文件的目录不存在
            file.getParentFile().mkdirs(); //创建目录
            
        }
        
        //2: 实例化OutputString 对象
        OutputStream output = new FileOutputStream(file);
        
        //3: 输出的内容
        
        String msg = "HelloWorld";
        //将字符串变为字节数组
        byte data[] = msg.getBytes();
        output.write(data);
        //4: 资源操作的最后必须关闭
        output.close();
        
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_42043101/article/details/85991978