Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 随机访问文件以读取xml文件_Java - Fatal编程技术网

Java 随机访问文件以读取xml文件

Java 随机访问文件以读取xml文件,java,Java,我正在尝试使用RandomAccessFile来读取xml文件。问题是,在文件结束之前,我希望一次只读取一定长度的内容 ReadUTF() read entire lines in the file which I do not want Read(byte,start,end) seems what I need, but it is readying in byte so it doesnt contain the actual text of the read content. 有没有一

我正在尝试使用RandomAccessFile来读取xml文件。问题是,在文件结束之前,我希望一次只读取一定长度的内容

ReadUTF() read entire lines in the file which I do not want
Read(byte,start,end) seems what I need, but it is readying in byte so it doesnt contain the actual text of the read content.
有没有一种方法可以使用RandomAccessFile一次读取特定长度的xml文件


谢谢。

readUTF读取单个UTF编码字符串,该字符串以无符号16位长度开头,后跟字符串。因此,它可以包含许多行,但不能用于读取文本文件

RandomAccessFile是为二进制格式设计的,所以很少支持读取文本


您是否尝试过使用BufferedReader和skip()进行随机访问?

您可以使用
RandomAccessFile
getChannel()
方法访问文件的一部分

例如,这里我映射了一个非常大的xml文件(2go)的位置100处开始的2000个字节

编辑(见下面的评论)

它不仅适用于单字节编码,请参阅此测试:

FileOutputStream fop = new FileOutputStream("/home/alain/Bureau/utf16.txt");
try (OutputStreamWriter wr = new OutputStreamWriter(fop, "UTF-16")) {
    wr.write("test test toto 测");
}

FileChannel channel = new RandomAccessFile("/home/alain/Bureau/utf16.txt", "r").getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
Charset chars = Charset.forName("UTF-16");
CharBuffer cbuf = chars.decode(buffer);
System.out.println("buffer = " + cbuf);
输出:

缓冲区=测试toto测


你为什么要这样做?xml不完全是随机访问格式。这仅适用于1。您使用的字符编码与xml文件和2的字符编码匹配。它是单字节编码。风险最大…@jtahlborn用户必须知道其文件的编码是的。但它不仅仅适用于单字节编码。查看编辑。您的编辑仅适用于utf-16编码,因为您正确选择了起始边界。但是,如果您从一个奇数字节开始,它将被破坏。如果使用utf-8,则无法选择“正确”的起始字节。@jtahlborn当然,如果使用utf-16,则只能使用2的倍数。对我来说,这不是一个很难的要求,如果你这么认为的话,这是你的权利。@jtahlborn
如果你在使用utf-8,就不可能选择一个“正确”的起始字节,你在说什么,更简单的情况是,在示例中用utf-8替换utf-16。如果从5开始,则显示
testtoto测。再简单不过了。。。
FileOutputStream fop = new FileOutputStream("/home/alain/Bureau/utf16.txt");
try (OutputStreamWriter wr = new OutputStreamWriter(fop, "UTF-16")) {
    wr.write("test test toto 测");
}

FileChannel channel = new RandomAccessFile("/home/alain/Bureau/utf16.txt", "r").getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
Charset chars = Charset.forName("UTF-16");
CharBuffer cbuf = chars.decode(buffer);
System.out.println("buffer = " + cbuf);