帮我用Java代码封装一个实现I/O流操作的方法
时间: 2023-04-04 16:01:00 浏览: 67
好的,以下是Java代码封装一个实现I/O流操作的方法的示例:
```java
public static String readFromFile(String filePath) {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
public static void writeToFile(String filePath, String content) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
```
以上代码中,readFromFile方法可以读取指定文件的内容并返回一个字符串,writeToFile方法可以将指定字符串写入指定文件中。这两个方法都使用了Java的I/O流操作。