输入输出流(IO)—文件字节流(FileInputStream & FileOutputStream)的基本操作及运用

时间:2022-04-20 04:51:19

FileInputStream类是InputStream类的子类,称为文件字节输入流。按字节读取文件中的数据。

构造方法:FileInputStream(String name)

                    FileInputStream(File file)

读取文件并输出:

public void test() throws IOException{
File file = new File("hello.txt");
FileInputStream in = null;
try{
in = new FileInputStream(file);
int a = in.read();
String str = new String();
while(a  != -1){
str += (char)a;
a = in.read();
}
System.out.println(str);
}catch(IOException e){
System.out.println(e);
}
}

输出结果为:文件hello.txt中的内容。


FileOutputStream类是OutputStream类的子类,称为文件字节输出流。提供基本的文件按字节写入能力。

构造方法:FileOutputStream(String name)

                    FileOutputStream(File file)

写入文件并输出:

public void test1(){
File file = new File("hello.txt");
byte b[] = "Welcome to read my blog!".getBytes();//字符串中的内容为将写入的内容,需调用getBytes()函数转换为字节形式
FileOutputStream out = null;
FileInputStream in = null;
try{
out = new FileOutputStream(file);
out.write(b);
out.flush();
in = new FileInputStream(file);
int n = 0;
while((n = in.read(b, 0, 1))   != -1){
String str = new String(b,0,n);
System.out.println(str);
}
}catch(IOException e){
System.out.println(e);
}
finally{
try{
out.close();
}catch(IOException e){
System.out.println(e);
}
}

}

输出结果为:Welcome to read my blog!      //此处内容与写入内容一致。


文件字节流的应用:存在一个已知文件oldfile,用文件字节流进行复制到新的文件newfile,并输出newfile中的内容

public void CopyFile(String oldFilename,String newFilename){
File nfile = new File(newFilename);
File ofile = new File(oldFilename);
FileOutputStream out = null;
FileInputStream in = null;
String str = new String();
try{
in = new FileInputStream(ofile);
int a = in.read();
while(a  != -1){
str += (char)a;
a = in.read();
}
}catch(IOException e){
System.out.println(e);
}
byte b[] = str.getBytes();
try{
out = new FileOutputStream(nfile);
out.write(b);
out.flush();
out.close();
}catch(IOException e){
System.out.println(e);
}

}

@Test
public void test2() throws IOException{
File oldfile = new File("hello.txt");
File newfile = new File("hel.txt");
FileInputStream in = null;
CopyFile(oldfile.getName(),newfile.getName());
try{
in = new FileInputStream(newfile);
int a = in.read();
String str = new String();
while(a  != -1){
str += (char)a;
a = in.read();
}
System.out.println(str);
}catch(IOException e){
System.out.println(e);
}

}

输出结果为:文件 oldfile 中的内容。