这里的输入和输出是相对于我们的java代码而言的,所谓字节输入流,也就是读取到我们的程序中,字节输出流是写入到我们的文件中
字节输入流
InputStream:这个抽象类是表示输入字节流的所有类的超类,这是它的部分方法 FileInputStream:是InputStream的子类,其构造方法如下
这里演示一个读取a.txt的文件,这里的文件我写的是hello world,这样如果下面不写n会出现bug import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream;
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:这个抽象类是表示字节输出流的所有类的超类,下面是他的方法
FileOutputStream: 是OutputStream的子类,其构造方法如下
这里演示读取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(); } } } 更多java学习资料可关注:itheimaGZ获取 |