java Io输入输出

2021-03-10 20:28

阅读:642

标签:catch   app   uil   ati   bsp   nal   except   rgb   output   

inputstream输入流

/**
 * 从文件中读取数据
 * @param args
 * @throws Exception
 */
public static void main(String[] args)throws Exception {
    String filePath = "C:/Users/zwk/Desktop/1.txt";
    InputStream in = new FileInputStream(filePath);
    //临时存放读取的数据,若文件超出1024,多次读取,每次读取1024,直到读取完成
    //可以改变1024的大小,减少或增加读取的次数
    byte[] b = new byte[1024];
    int l;
    StringBuilder sb = new StringBuilder();
    while ((l = in.read(b)) != -1){
        //将读取的子节数组转换为字符串
        sb.append(new String(b,0,l,"UTF-8"));
    }
}

inputstream输入流2

public static void main(String[] args)throws Exception {
    String filePath = "C:/Users/zwk/Desktop/2.txt";
    InputStream in = new FileInputStream(filePath);
    //临时存放读取的数据,若文件超出1024,多次读取,每次读取1024,直到读取完成
    //可以改变1024的大小,减少或增加读取的次数
    byte[] b = new byte[1024];
    int l;  //读取的长度
    //StringBuilder sb = new StringBuilder();
    //将读取的数据存放到输出缓存流中
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while ((l = in.read(b)) != -1){
        //将读取的子节数组转换为字符串
        //sb.append(new String(b,0,l,"UTF-8"));
        //存放到输出流中
        bos.write(b,0 , l);
    }
    System.out.println(new String(bos.toByteArray(),0,bos.toByteArray().length,"utf-8"));
}

输出流输入流

 /**
 * 从文件中读取数据并输出到另外一个文件上
 * @param args
 */
public static void main(String[] args) {
    //从文件中读取
    InputStream in = null;
    OutputStream out = null;
    try {
        String filePath = "C:/Users/zwk/Desktop/2.txt";
        in = new FileInputStream(filePath);

        byte[] b = new byte[1024];
        int l;
        StringBuilder sb = new StringBuilder();

        while ((l = in.read(b)) != -1){
            sb.append(new String(b,0,l,"UTF-8"));
        }
        //输出到文件中
        out = new FileOutputStream("C:/Users/zwk/Desktop/3.txt");
        out.write(sb.toString().getBytes());
    } catch (Exception e){

    } finally { //关闭资源
        if(in != null){
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(out != null){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

 

java Io输入输出

标签:catch   app   uil   ati   bsp   nal   except   rgb   output   

原文地址:https://www.cnblogs.com/lazyli/p/14142079.html


评论


亲,登录后才可以留言!