输入输出流:Java文件读写操作实战案例
在Java中,输入输出流是进行文件读写操作的基础工具。以下是一些实用的案例:
文件的创建与写入:
// 创建一个文件
File file = new File("example.txt");
// 如果文件不存在,尝试创建并写入内容
if (!file.exists()) {
try (OutputStream os = new FileOutputStream(file)) {
String content = "Hello, World!";
os.write(content.getBytes());
os.close();
} catch (IOException e) {
System.out.println("Error occurred while creating file: " + e.getMessage());
}
}
文件的读取:
// 读取文件内容
try (BufferedReader br = new BufferedReader(new FileReader(file)))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error occurred while reading file: " + e.getMessage());
}
文件的删除:
// 删除文件
try {
if (file.exists()) {
file.delete();
System.out.println("File deleted successfully.");
} else {
System.out.println("File doesn't exist to delete.");
}
} catch (IOException e) {
System.out.println("Error occurred while deleting file: " + e.getMessage());
}
以上就是Java文件读写操作的一些基本案例,通过这些,你可以理解和掌握Java文件处理的基本技巧。
还没有评论,来说两句吧...