我们只介绍几种常用的流,文件专属的流有FileInputStream,FileOutputStream,FileReader,FileWriter。
FileInputStream和FileReader的区别:FileInputStream是字节流,是按照字节的方式来进行读取的,属于万能流,什么类型的文件都是可以读取的,包括图片、声音、文本、视频文件等。而FileReader是字符流,是按照字符的方式进行读取的,只能读取纯文本文件,无法读取word文件。
下面来演示一下使用FileInputStream来实现声音的读取。
public class IOStream{
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("Need You Now-Shane Filan.mp3");
int readCount;
while((readCount = fis.read()) != -1){
System.out.println(readCount);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行结果:最后输出的就是ASCII码
使用FileReader来读取文本文件:
public class IOReader{
public static void main(String[] args) {
FileReader fr = null;
try {
fr = new FileReader("LICENSE.txt");
char[] chars = new char[1024];
int readCount = 0;
while ((readCount = fr.read(chars)) != -1){
System.out.println(new String(chars,0,readCount));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fr != null){
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行的结果如下:
下面我们来使用FileInputStream和FileOutputStream来实现文件的复制。其实文件的复制也就是对文件进行边读边写的操作。
public class CopyFile{
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("D:aaa.txt");
fos = new FileOutputStream("D:bbb.txt");
byte[] bytes = new byte[1024];
int readCount = 0;
while ((readCount = fis.read(bytes)) != -1){
fos.write(bytes,0,readCount);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
以上是我关于IO流中文件专属流的认识,如有错误或者侵权的地方,请联系我改正或者删除。欢迎大家和我一起探讨关于java和算法的知识。