[Java基础]复制文件的异常处理try...catch...finally的做法
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Java基础]复制文件的异常处理try...catch...finally的做法相关的知识,希望对你有一定的参考价值。
代码如下:
package ErrorOperatorPack;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyFileDemo01 {
public static void main(String[] args)
{
}
private static void method() {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("fr.txt");
fw = new FileWriter("fw.txt");
char[] chs = new char[1024];
int len;
while((len = fr.read())!=-1)
{
fw.write(chs,0,len);
}
}catch (IOException e)
{
e.printStackTrace();
}finally {
if (fr!=null)
try {
fr.close();
}catch (IOException e)
{
e.printStackTrace();
}
if (fw!=null)
{
try{
fw.close();
}catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
代码如下:
package ErrorOperatorPack;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyFileDemo02 {
public static void main(String[] args)
{
}
private static void method()
{
try(FileReader fr = new FileReader("fr.txt");
FileWriter fw = new FileWriter("fw.txt");)
{
char[] chs = new char[1024];
int len;
while((len = fr.read())!=-1)
{
fw.write(chs,0,len);
}
}catch (IOException e)
{
e.printStackTrace();
}
}
}
代码如下:
package ErrorOperatorPack;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyFileDemo03 {
public static void main(String[] args)
{
}
private static void method() throws IOException {
FileReader fr = new FileReader("fr.txt");
FileWriter fw = new FileWriter("fw.txt");
try(fr;fw)
{
char[] chs = new char[1024];
int len;
while((len = fr.read())!=-1)
{
fw.write(chs,0,len);
}
}catch (IOException e)
{
e.printStackTrace();
}
}
}
以上是关于[Java基础]复制文件的异常处理try...catch...finally的做法的主要内容,如果未能解决你的问题,请参考以下文章