Java教程

JAVA,字节流文件读写

本文主要是介绍JAVA,字节流文件读写,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

写入文件:

package com.java.day28OutputStream;

import java.io.FileOutputStream;
import java.io.IOException;

public class OutputStream01 {
    public static void main(String[] args){
        output();
    }

    public static void output(){
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("D:\\IdeaProjects\\StudyJava\\day01\\src\\com\\java\\day28OutputStream\\a.txt");
            String str = "Hello World";
            // todo getBytes方法将字符串转为byte数组
            fos.write(str.getBytes());
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (fos !=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

运行效果:

 

 读取文件:

package com.java.day29InputStream;

import java.io.FileInputStream;
import java.io.IOException;

public class InputStream {
    public static void main(String[] args) {
        input();
    }

    public static void input() {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("D:\\IdeaProjects\\StudyJava\\day01\\src\\com\\java\\day28OutputStream\\a.txt");
            int len = 0;
            while ((len = fis.read()) !=-1){
                System.out.print((char) len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

运行效果:

 

 

这篇关于JAVA,字节流文件读写的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!