Java IO字节输入输出流
Java的输入输出功能来自java.io 包中InputStream类、OutputStream类
OutPutStream(输出流) 使用:
// 文件路径
File f1 = new File("C:\\Users\\Yxb\\Desktop\\test.txt");
// 因为OutputStream是抽象类 没法实例化 通过向上转型实例化子类来使用
OutputStream out = new FileOutputStream(f1);
通过.write()方法向文件中写入内容
out.write(97);
可以看到写入的内容是a 这是因为它是根据ASCII码表来写入内容的。我们如果向写入东西还要对照ASCII码表来输入所对应的十进制数字,这样效率太慢了,那么我们应该怎样写入自己想要写入的内容呢?
我们可以将想要写入的内容写在String类型中,然后通过String类的.getBytes()方法将这些内容变成byte数组,然后通过.write()方法向文件中写入内容,参数为byte数组
String str = "97";
out.write(str.getBytes());
这样就可以写入我们想要写入的内容了。
可是现在还有一个问题,如果我们每次运行代码它都会将原本的内容替换成我们想要输入的内容,没法接着后面继续写入。这是因为它的FileOutputStream参数后面会默认是false,我们只需要改成true即可
OutputStream out = new FileOutputStream(f2,false);// (默认false)替换原本内容
OutputStream out = new FileOutputStream(f2,true);// 在原本的内容后面继续写入
InputStream(输入流) 使用:
File f1 = new File("C:\\Users\\Yxb\\Desktop\\test.txt");
InputStream in = new FileInputStream(f1);
.read()进行读操作
// 如果到达流末尾而没有可用的字节,则返回值 -1
int read = in.read();
// read为ASCII码表中所对应的十进制数字,使用强制类型转换变成char类型
System.out.println((char)read);
这样我们每次就可以读取一个字节,这样效率太慢了。因为到达流末尾而没有可用的字节,则返回值 -1,那么我们可以使用循环来打印所有内容
int n;
while((n = in.read())>0){
System.out.print((char)n);
}
或者
// 声明一个byte数组,长度随意
byte[] b = new byte[10];
// 声明一个int类型的值
int i2;
// while循环,将.read(b)的值赋值给i2,判断条件如果i2大于0则证明数组中有值,否则结束循环
while ((i2 = in.read(b)) > 0) {
// String的有参构造方法
// String s = new String(byte[] b); 将byte数组传入String的构造方法中,打印s即可
String s = new String(b,0,i2);
System.out.print(s);
}
小案例
将某个磁盘中的某个文件复制到桌面
public class InputStreamTest02 {
public static void main(String[] args) throws IOException {
/*
* 照片
* */
// 找到文件路径
File f1 = new File("E:\\Test\\TestPic.jpeg");
// 粘贴的路径
File f2 = new File("C:\\Users\\Yxb\\Desktop\\paste\\pastePic.jpeg");
// 实例化输入输出流
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
// 定义一个byte数组长度为1024(长度多少都可以,长度如果太短运行效率就会慢,过长占用内存)
byte[] b = new byte[1024];
int n;
while ((n = in.read(b)) > 0) {
// 写入byte数组中的值,从第0个字节开始写入,长度为n
out.write(b, 0, n);
}
/*
* 视频
* */
File f3 = new File("E:\\Test\\TestVideo.mp4");
File f4 = new File("C:\\Users\\Yxb\\Desktop\\paste\\pasteVideo.mp4");
InputStream in2 = new FileInputStream(f3);
OutputStream out2 = new FileOutputStream(f4);
byte[] b2 = new byte[2048];
int n2;
while ((n2 = in2.read(b2)) > 0) {
out2.write(b2, 0, n2);
}
}
}
运行后效果图:
还没有评论,来说两句吧...