字节流
输入流与输出流
字节输入流:InputStream:字节输入流的所有类的超类。
字节输出流:OutputStream:输出字节流的所有类的超类
字符输入流:Reader:字符输入流的所有类的超类。
字符输出流:Writer:输出字符流的所有类的超类
字节输入流
- 读取数据
package com.tian.text;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Test2 {
public static void main(String[] args) throws IOException {
FileInputStream input = new FileInputStream("D:/file1/1.txt");
byte[] data = new byte[1024];// 1次最多读取1K
int len=-1;
while((len=input.read(data))!=-1){
System.out.println(new String(data,0,len));
}
input.close();
}
}
字节输出流
- 写数据进去文件
package com.tian.text;
import java.io.*;
public class Test2 {
public static void main(String[] args) throws IOException {
OutputStream output = new FileOutputStream("D:\\file1\\1.txt");
/* output.write(97);//a
output.write(98);//b
output.write(99);//c */
String str="我想测试一下数据能不能写进去";
byte[] data=str.getBytes();
output.write(data);
output.close();
}
}
-
两个小问题
怎么换行
windows: \r\n
linux: \n
mac: \r
for (int i = 0; i < 10; i++) {
output.write("hello".getBytes());
output.write("\r\n".getBytes());
}
怎么追加
- 如果第二个参数为true,则字节将写入文件的末尾而不是开头
OutputStream output = new FileOutputStream("D:\\file1\\1.txt",true);
复制任意文件
代码演示
package com.tian.text;
import java.io.*;
public class Test2 {
public static void main(String[] args) throws IOException {
InputStream input = null;
OutputStream output = null;
// 读取文件--->字节输入流
try {
input = new FileInputStream("D:\\file1\\1.txt");
output = new FileOutputStream("D:\\file2\\2.txt");
byte[] data = new byte[1024];
int len = -1;
System.out.println("准备进行文件复制");
while ((len = input.read(data)) != -1) {
output.write(data, 0, len);
}
System.out.println("文件复制完成");
} catch (IOException e) {
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
}
}
}
}
}