Java中IO流的读写操作,如何处理异常情况?实例展示
在Java中,IO流的读写操作通常会使用try-catch语句来处理可能发生的异常。
以下是一些常见的IO流操作以及对应的异常处理示例:
- FileInputStream - 读取文件内容
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("test.txt")) {
byte[] buffer = new byte[1024];
int length = fis.read(buffer);
while (length != -1) {
System.out.println(new String(buffer, 0, length))));
length = fis.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error reading file: " + e.getMessage());
}
}
}
- PrintWriter - 写入数据到文件或打印
import java.io.FileWriter;
import java.io.IOException;
public class PrintWriterExample {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("test.txt")) {
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println("Hello, World!");
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error writing to file: " + e.getMessage());
}
}
}
在上述示例中,如果文件不存在或者无法写入,FileInputStream
和FileWriter
会抛出异常。我们通过try-catch语句来捕获这些异常,并处理它们。
还没有评论,来说两句吧...