zoukankan      html  css  js  c++  java
  • Java输出文件到本地(输出流)

    package cn.buaa;
    
    import java.io.File;
    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 {
            
            //字节流
            byteOutStream();
            
            
            //字符流 (输出流中含有中文时使用字符流)
            charOutStream();
    
    }
        public static void charOutStream() throws Exception{
            // 1:利用File类找到要操作的对象
                File file = new File("D:" + File.separator + "demo" + File.separator + "test.txt");
                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("D:" + File.separator + "demo" + File.separator + "test.txt"); 
            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();
            
        }
    
    }
    
    
        
        
    
        
        
  • 相关阅读:
    08-12 NOIP模拟测试18
    08-09 NOIP模拟测试15
    08-11 NOIP模拟测试17
    08-10 NOIP模拟测试16
    08-07 NOIP模拟测试14
    08-03 NOIP模拟测试12
    [SDOI2011]拦截导弹
    08-01 NOIP模拟测试11
    零散知识点
    07-29 NOIP模拟测试10
  • 原文地址:https://www.cnblogs.com/StanLong/p/6414383.html
Copyright © 2011-2022 走看看