zoukankan      html  css  js  c++  java
  • Java文件流之字节流

    InputStream 与OutputStream是字节流中的输入流和输出流。

    public class FileStream {
    
        public static void main(String[] args) {
            FileStream fs = new FileStream();
            // String content =
            // fs.readFileWithInputStream("/home/rding/file/File1.txt");
            // System.out.println(content);
    
            fs.writeFileWithOutputStream("/home/rding/file/File3.txt", "Hello File3");
    
            // fs.copyFile("/home/rding/file/File3.txt",
            // "/home/rding/file/File4.txt");
    
        }
    
        public void copyFile(String srcPath, String descPath) {
            InputStream inStream = null;
            OutputStream outStream = null;
            try {
                inStream = new FileInputStream(srcPath);
                outStream = new FileOutputStream(descPath);
                int size = inStream.available();
                byte[] byteArr = new byte[size];
                inStream.read(byteArr);
                outStream.write(byteArr);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
        public void writeFileWithOutputStream(String filePath, String content) {
            OutputStream outStream = null;
            byte[] byteArr = content.getBytes();
            try {
            //注意,outStream第一次建立后,就不会更新了,必须关闭再重新建立 outStream
    = new FileOutputStream(filePath); // outStream = new FileOutputStream(new File(filePath));        // 如果传入参数true,则接着原来文件后面继续写,而不是覆盖源文件。 // outStream = new FileOutputStream(filePath, true); // outStream = new FileOutputStream(new File(filePath), true); outStream.write(byteArr); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (outStream != null) { try { outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } public String readFileWithInputStream(String filePath) { InputStream inStream = null; String result = ""; try { inStream = new FileInputStream(filePath); // inStream = new FileInputStream(new File(filePath)); int size = inStream.available(); byte[] byteArr = new byte[size]; inStream.read(byteArr); result = new String(byteArr); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } }
  • 相关阅读:
    移动端div移动
    js获取网页高度
    css cursor 的可选值(鼠标的各种样式)
    HTML5 拖动
    函数式编程中的常用技巧
    CoolShell Puzzle攻略[更新隐藏剧情]
    Web性能测试-词汇
    STM32库函数 断言机制 宏定义assert_param(expr)和assert_failed的使用方法
    arm汇编:伪指令ldr分析
    Altium designer 16 Mechanical1层之PCB 打样说明
  • 原文地址:https://www.cnblogs.com/lfdingye/p/7514065.html
Copyright © 2011-2022 走看看