1.使用FileInputStream读取文件
package peixun;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadByteStream {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("text.txt");
byte input[] = new byte[21];
fis.read(input);//读取字节流文件
String inputString = new String(input);//将字节流文件转换成字符串
System.out.println(inputString);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
2.使用FileOutputStream写入文件
package peixun;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteByteStrean {
public static void main(String[] args) throws FileNotFoundException {
try {
FileOutputStream fos = new FileOutputStream("textw.txt");//流的打开
String outString = "write 123456写出数据";
byte[] output = outString.getBytes();//流的写入,将文本文件获取为字节数组
fos.write(output);//流的读取
fos.close();//关闭流操作
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3.使用输入、输出流实现文件的拷贝
package peixun;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class CopyByByteStream {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("123.png");//读取文件数据
FileOutputStream fos = new FileOutputStream("123_new.png");
byte [] input = new byte[50];
while (fis.read(input) != -1) {
fos.write(input);//将数组写出到新的文件
}
fis.close();
fos.close();
System.out.println("done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.使用缓冲的字节流读写数据:
package peixun;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ReadByBufferedByteStream {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("1.mp4");
BufferedInputStream bis = new BufferedInputStream(fis,100000);//设置缓冲区大小,一般大于数组的大小。
FileOutputStream fos = new FileOutputStream("2.mp4");
BufferedOutputStream bos = new BufferedOutputStream(fos,100000);
byte [] input = new byte[100];//大型的文件对应的数组大一点,比较小的文件数组小一点。
int count = 0;
long before = System.currentTimeMillis();
while (bis.read(input) != -1) {
bos.write(input);
count++;
}
bis.close();
fis.close();
fos.close();
bos.close();
System.out.println("count:"+count);
System.out.println(System.currentTimeMillis()-before);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}