记忆系列-Java IO的字节输入输出流
本文最后更新于 2001 天前,其中的信息可能已经有所发展或是发生改变。

上一篇我自己写过java io 流的基础–分类:字节流和字符流。

那么这篇就先写字节流吧~(为了水多点文章没办法~)


字节输入输出基础流:InputStream、OutputSteam

但是呢,比较常用的两个字节流FileInputStream和FileOutputStream

FileInputStream

该流用于从文件读取数据,它的对象可以用关键字new来创建。

有多种构造方法可用来创建对象。

可以使用字符串类型的文件名来创建一个输入流对象来读取文件:

InputStream f = new FileInputStream(“D:/io/glj”);

也可以使用一个文件对象来创建一个输入流对象来读取文件。我们首先得使用File()方法来创建一个文件对象:
File f = new File(“D:/io/glj”);
InputStream ips= new FileInputStream(f);

创建了InputStream对象,就可以使用下面的方法:

FileOutputStream

该类用来创建一个文件并向文件中写数据。

如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件。

有两个构造方法可以用来创建FileOutputStream 对象。

使用字符串类型的文件名来创建一个输出流对象:

OutputStream f = new FileOutputStream(“C:/io/glj”);

也可以使用一个文件对象来创建一个输出流来写文件。我们首先得使用File()方法来创建一个文件对象:

File f = new File(“C:/io/glj”);
OutputStream ops = new FileOutputStream(f);

同理:创建了OutputStream对象,也就可以使用下面的方法:

FileOutputStream例子吧~

String destFile = "D:"+File.separator+"destfile.txt";
        String lineSeparator = System.getProperty("line.separator");
        String line = "g";
        String line2 = "l";
        String line3 = "j";
        try(FileOutputStream fos = new FileOutputStream(destFile)){
            fos.write(line.getBytes());
            fos.write(lineSeparator.getBytes());

            fos.write(line2.getBytes());
            fos.write(lineSeparator.getBytes());

            fos.write(line3.getBytes());
            //刷新输出流
            fos.flush();
            System.out.println("文件已经写入完成。地址:"+new File(destFile).getAbsolutePath());
        }catch (Exception e){
            e.printStackTrace();
        }

FileInputStream例子吧~

String destFile = "D:"+File.separator+"destfile.txt";
        try(FileInputStream fis = new FileInputStream(destFile)){
            int size =  fis.available() ;
            //根据输入流中的字节数创建byte数组
            byte[] array = new byte[size];
            //把数据读取到数组中
            fis.read( array ) ;
            String result = new String(array);
            System.out.println(result);
        }catch (Exception e) {
            e.printStackTrace();
        }

评论

  1. Windows Chrome 63.0.3239.132
    5 年前
    2019-9-01 17:01:03

    非技术的路过。

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇