因为使用 IO 读写 String 在开发中不是经常使用,总是忘记,所以在此记录一下。
String dateString = "2012-1-2";
File file = new File("D:/test");
FileOutputStream fileOutputStream = new FileOutputStream(file);
// write1
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(fileOutputStream));
bufferedWriter.write(dateString);
bufferedWriter.close();
// write2
DataOutputStream dataOutputStream = new DataOutputStream(
fileOutputStream);
dataOutputStream.write(dateString.getBytes());
// write3
FileChannel writeFileChannel = fileOutputStream.getChannel();
ByteBuffer writeByteBuffer = ByteBuffer.allocate(dateString
.length());
writeByteBuffer.put(dateString.getBytes());
writeByteBuffer.flip();
writeFileChannel.write(writeByteBuffer);
fileOutputStream.close();
FileInputStream fileInputStream = new FileInputStream(file);
// read1
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(fileInputStream));
System.out.println(bufferedReader.readLine());
// read2
FileChannel readFileChannel = fileInputStream.getChannel();
ByteBuffer readByteBuffer = ByteBuffer.allocate(1024);
while (readFileChannel.read(readByteBuffer) != -1) {
System.out.print(((ByteBuffer) (readByteBuffer.flip()))
.asCharBuffer().get(0));
readByteBuffer.clear();
}
fileInputStream.close();
本文通过示例介绍如何使用Java进行String的文件读写操作,包括使用BufferedWriter、DataOutputStream及FileChannel等方式写入,并展示了如何读取这些数据。
326

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



