Java中的文件操作,如读写、删除等
在Java中,我们可以使用内置的java.io
包进行文件操作。以下是一些基本的操作:
创建文件 -
FileWriter
或PrintWriter
File file = new File("path/to/your/file.txt");
try (FileWriter writer = new FileWriter(file)) {
// write to the file
} catch (IOException e) {
e.printStackTrace();
}
读取文件 -
BufferedReader
orFileReader
File file = new File("path/to/your/file.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(file)))) {
// read from the file
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
写入追加模式 -
FileWriter
File file = new File("path/to/your/file.txt");
try (FileWriter writer = new FileWriter(file, true)) {
// write to the file in append mode
} catch (IOException e) {
e.printStackTrace();
}
删除文件 -
File
File file = new File("path/to/your/file.txt");
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
}
以上就是Java中进行基本文件操作的一些示例。
还没有评论,来说两句吧...