我希望以不同的偏移量将数据写入文件。例如,在第0个位置,在第(大小/第2)个位置,在第(大小/第4)个位置等等大小表示要创建的文件的文件大小。这可能没有创建不同的文件部分,并加入他们?将数据字节写入java中偏移处的文件
6
A
回答
6
那么你可以使用RandomAccessFile写信给你喜欢的任何地方 - 只需使用seek
来到正确的位置并开始写作。
然而,这不会在那些地方插入字节 - 它只是覆盖他们(或者在末尾添加数据如果你正在写过去的当前文件长度的目的,当然)。目前还不清楚这是否是你想要的。
0
您要找的是Random access files
。从official sun java tutorial site -
随机访问文件允许一个 文件的内容不连续,或随机访问。要随机访问文件,请打开文件,查找特定位置,然后读取或写入该文件。
SeekableByteChannel接口可以实现此功能。 SeekableByteChannel接口扩展了当前位置的概念 的通道I/O。通过方法,您可以设置或查询 的位置,然后您可以从该位置读取数据或将数据写入 。 API包含了几下,简单易用,方法:
位置 - 返回通道的当前位置
位置(长) - 设置通道的位置
读(字节缓冲区) - 读取字节到从通道缓冲区
写(字节缓冲区) - 将字节从缓冲器到通道
截断(长) - 截断连接到通道
和示例的文件(或其他实体),它有提供 -
String s = "I was here!\n";
byte data[] = s.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);
ByteBuffer copy = ByteBuffer.allocate(12);
try (FileChannel fc = (FileChannel.open(file, READ, WRITE))) {
// Read the first 12
// bytes of the file.
int nread;
do {
nread = fc.read(copy);
} while (nread != -1 && copy.hasRemaining());
// Write "I was here!" at the beginning of the file.
// See how they are moving back to the beginning of the
// file?
fc.position(0);
while (out.hasRemaining())
fc.write(out);
out.rewind();
// Move to the end of the file. Copy the first 12 bytes to
// the end of the file. Then write "I was here!" again.
long length = fc.size();
// Now see here. They are going to the end of the file.
fc.position(length-1);
copy.flip();
while (copy.hasRemaining())
fc.write(copy);
while (out.hasRemaining())
fc.write(out);
} catch (IOException x) {
System.out.println("I/O Exception: " + x);
}
0
如果这不是你可以阅读整个事情比编辑阵列一个巨大的文件:
public String read(String fileName){
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
}
public String edit(String fileContent, Byte b, int offset){
Byte[] bytes = fileContent.getBytes();
bytes[offset] = b;
return new String(bytes);
]
,然后将它写回文件(或只是删除旧的和写将字节数组转换为同名的新文件)
相关问题
- 1. 在字节的特定偏移处写入。缓冲区
- 2. 当写入.bmp文件时发生字节偏移
- 3. 将字节写入文件
- 4. 读入偏移量的字节数组?
- 5. java:找到字符偏移量,从文件起始处的文本文件中的字的偏移量?
- 6. Java在文件中写入字节
- 7. 将字符串写入文件作为Java中的字节
- 8. 从Java将字节数组写入Java数据库作为图像或文件
- 9. 将字节数组写入文件夹
- 10. 将数据写入节俭文件
- 11. 检测写入数据的偏移量
- 12. 将2D字节数组写入文本文件Java
- 13. 无法将偏移量数据写入kafka-storm中的zookeeper
- 14. 在Java中写入偏移量?
- 15. 读取字节数组与将字节数组写入文件
- 16. 用值y将x字节写入java中的文件
- 17. 如何将字节数组写入Java文件
- 18. Python基于偏移量写入文件
- 19. Java Servlet - 将数据写入文件
- 20. Java以字节格式将字节从字节缓冲区写入文件
- 21. 去。将[]字节写入文件结果为零字节文件
- 22. Python将字节写入文件
- 23. 如何在Java中从字节数组写入WAV文件?
- 24. 如何将数据写入Java中的文本文件
- 25. Java - 在给定偏移量处读取字节
- 26. 将所有字节0x00-0xFF写入批处理文件
- 27. 将数据写入文件
- 28. 将数据写入文件
- 29. 将数据写入文件
- 30. 将ODS导入MySQL:偏移数据
转到[这里](http://docs.oracle.com/javase/tutorial/essential/io/rafs.html)。 – 2013-03-27 07:03:29