Java中字節輸入輸出流

這裏的輸入和輸出是相對於咱們的java代碼而言的,所謂字節輸入流,也就是讀取到咱們的程序中,字節輸出流是寫入到咱們的文件中java

字節輸入流it

InputStream:這個抽象類是表示輸入字節流的全部類的超類,這是它的部分方法
 
 
FileInputStream:是InputStream的子類,其構造方法以下
 io

這裏演示一個讀取a.txt的文件,這裏的文件我寫的是hello world,這樣若是下面不寫n會出現bug
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;class

public class Main {
    public static void main(String[] args) {
        try {
            InputStream in = new FileInputStream("C:\Users\Administrator\Desktop\a.txt");
            byte[] bytes = new byte[2]; //這裏我寫2是爲了演示,通常寫1024吧
            int n;
            while ((n = in.read(bytes)) != -1) {
                String s = new String(bytes,0,n);//這個不能直接寫bytes,否則可能會讀錯
                System.out.println(s);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
運行結果:
 
字節輸出流
OutputStream:這個抽象類是表示字節輸出流的全部類的超類,下面是他的方法import

FileOutputStream: 是OutputStream的子類,其構造方法以下
 bug

這裏演示讀取a.txt文件寫入到b.txt文件中的操做程序

import java.io.*;方法

public class Main {
    public static void main(String[] args) {
        try {
            InputStream in = new FileInputStream("C:\Users\Administrator\Desktop\a.txt");
            OutputStream os = new FileOutputStream("C:\Users\Administrator\Desktop\b.txt");
            byte[] bytes = new byte[2];
            int n;
            while ((n = in.read(bytes)) != -1) {
                os.write(bytes,0,n); //這裏一樣的不寫n也會出現bug
            }
            in.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}im

相關文章
相關標籤/搜索