Java文件读写:File类的常用方法示例
在Java中,java.io.File
是操作文件和目录的主要工具。以下是一些常用的File类方法:
- 创建文件或目录:
```java
// 创建一个新文件
File file = new File(“myFile.txt”);
file.createNewFile();
// 创建目录
File dir = new File(“myDirectory”);
dir.mkdirs();
2. **获取文件路径**:
```java
String filePath = file.getAbsolutePath(); // 获取绝对路径
检查文件是否存在:
boolean fileExists = file.exists(); // 检查文件是否已存在
读取文件内容:
try (BufferedReader br = new BufferedReader(new FileReader(file)))) {
String content = br.readLine();
System.out.println("File content: " + content);
} catch (IOException e) {
e.printStackTrace();
}
写入文件内容:
try (PrintWriter writer = new PrintWriter(file)) {
writer.println("This is a test message.");
} catch (IOException e) {
e.printStackTrace();
}
请根据实际需求选择并使用上述方法。
还没有评论,来说两句吧...