//向指定文件中写入数据
public static void writeDataToFile(String content, String filePath) {
try {
//创建一个文件输出流
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
//获取文件输入流的通道
FileChannel channel = fileOutputStream.getChannel();
//创建一个字节缓冲区,并制定长度
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//将要写入到文件中的内容放入缓冲区
byteBuffer.put(content.getBytes());
//将byteBuffer进行读写反转
byteBuffer.flip();
//将byteBuffer的内容写入通道
channel.write(byteBuffer);
//资源关闭
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//从指定文件中读取数据
public static String readDataFromFile(String filePath) {
String result = "";
try {
//获取文件输入流
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
//获取文件输入流的通道
FileChannel fileChannel = fileInputStream.getChannel();
//创建字节缓冲区对象,用于接收通道中的数据
ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
//将通道中的数据写入缓冲区
fileChannel.read(byteBuffer);
//将缓冲区的数据返回
result = new String(byteBuffer.array());
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
java读写文件
最新推荐文章于 2024-12-04 11:46:54 发布
928

被折叠的 条评论
为什么被折叠?



