节点流(文件流) FileInputStream、FileOuputStrea、FileReader、FileWriter的用法(实现文件的复制)
1. FileInputStream、FileOuputStream的用法和注意点
- FileInputStream从硬盘存在的一个文件中,读取其内容到程序中,使用FileInputStream,要读取的文件一定要存在,否则抛FileNotFounderException
- read():读取文件的一个字节。当执行到文件结尾时,返回-1
- 要使用try-catch的方式处理如下的异常更合理:保证流的关闭操作一定可以执行,最好不要直接使用throws
- 输出流的物理文件可以不存在,当执行过程中,若不存在,会自动的创建,若存在,会将原有的文件覆盖
- 接收读取数据的数组长度可根据实际文件大小设置。
2.FileInputStream读取文件并打印到控制台
@Test
public void testFileInputStream1() {
FileInputStream fis = null;
try {
File file = new File("hello.txt");
fis = new FileInputStream(file);
int b;
while((b = fis.read())!= -1) {
System.out.print((char)b);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3. FileOutputStream将程序文件输出到指定文件
@Test
public void testFileOutputStream(){
File file = new File("hello2.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(new String("I love Java forever!").getBytes());
}catch(Exception e) {
e.printStackTrace();
}
finally {
if( fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4. FileInputStream 与 FileOutputStream结合实现文件(图片,视屏等)的复制。
public static void CopyFile(String src,String dest) {
File file1 = new File(src);
File file2= new File(dest);
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file1);
fos = new FileOutputStream(file2);
byte [] b = new byte[20];
int len;
while((len = fis.read(b)) != -1) {
fos.write(b, 0, len);
}
} catch (Exception 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();
}
}
}
}
1. FileReader、FileWriter的用法和注意点
- 两个都是针对文本文件的节点流,传输音频或者图形会出错。
- FileReader、FileWriter结合实现文本的复制
- 注意:word文档,ppt等并不是文本,需用字节流复制。
@Test
public void testFileReaderWriter(){
FileReader fr = null;
FileWriter fw = null;
try{
File src = new File("hello.txt");
File dest = new File("hello3.txt");
fr = new FileReader(src);
fw = new FileWriter(dest);
char[] c = new char[24];
int len;
while((len = fr.read(c)) != -1){
fw.write(c, 0, len);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(fw != null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fr != null){
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}