IO异常的处理
public class Demo1 {
public static void main(String[] args) {
try {
readTest();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readTest() throws IOException {
try {
File file = new File("G:\\aaaa.txt");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buf = new byte[1024];
int length = 0;
while((length = fileInputStream.read(buf)) != -1) {
System.out.println(new String(buf, 0, length));
}
} catch(IOException e) {
throw e;
}
fileInputStream.close();
}
}
public class Demo2 {
public static void main(String[] args) {
readTest();
}
public static void readTest() {
FileInputStream fileInputStream = null;
try {
File file = new File("G:\\a.txt");
fileInputStream = new FileInputStream(file);
byte[] buf = new byte[1024];
int length = 0;
while((length = fileInputStream.read(buf)) != -1) {
System.out.println(new String(buf, 0, length));
}
} catch(IOException e) {
System.out.println("读取文件资源出错了...");
throw new RuntimeException(e);
} finally {
try {
if(fileInputStream != null) {
fileInputStream.close();
System.out.println("关闭资源成功!");
}
} catch(IOException e) {
System.out.println("关闭资源出错了...");
throw new RuntimeException(e);
}
}
}
}
public class Demo3 {
public static void main(String[] args) {
copy();
}
public static void copy() {
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
try {
File inFile = new File("G:\\1.jpg");
File destFile = new File("F:\\1.jpg");
fileInputStream = new FileInputStream(inFile);
fileOutputStream = new FileOutputStream(destFile);
byte[] buf = new byte[1024];
int length = 0;
while((length = fileInputStream.read(buf)) != -1) {
fileOutputStream.write(buf, 0, length);
}
} catch(IOException e) {
throw new RuntimeException(e);
} finally {
try {
if(fileOutputStream != null) {
fileOutputStream.close();
System.out.println("输出流对象关闭成功!");
}
} catch(IOException e) {
System.out.println("输出流对象关闭失败..");
throw new RuntimeException(e);
} finally {
try {
if(fileInputStream != null) {
fileInputStream.close();
System.out.println("输入流对象关闭成功!");
}
} catch(IOException e) {
System.out.println("输入流对象关闭失败..");
throw new RuntimeException(e);
}
}
}
}
}