我正在使用谷歌翻译,我希望这个问题能得到很好的理解。
有一件事我不理解随机访问文件.No理解程序如何工作,但它的工作。
这是我的节目:
// ---------------------------------------------
RandomAccessFile RandomAccessFile = new RandomAccessFile ( " pathfile ", " r");
byte [] document = new byte [ ( int) randomAccessFile.length ()] ;
randomAccessFile.read (document) ;
// ---------------------------------------------在第1行中,我访问第2行中读取的文件,我创建一个字节数组对象,大小与第3行中的文件读取字节数组的大小相同。
但是从来没有转储字节数组上的文件。
我认为这个项目应该是这样的:
/ / ---------------------------------------------
RandomAccessFile RandomAccessFile = new RandomAccessFile ( " pathfile ", " r");
byte [] document = new byte [ ( int) randomAccessFile.length ()] ;
// Line changed
document = randomAccessFile.read();
// ---------------------------------------------java文档说:
randomAccessFile.read() ;
Reads a byte of data from this file . The byte is returned as an integer in
the range 0 to 255 ( 0x00- 0x0ff ) .只返回字节数,而不返回字节数。
有人可以向我解释,这一行是如何用这条语句转储字节[]变量文档中的字节的?
randomAccessFile.read (document) ;谢谢!!
//
另一个例子是:
我将此方法与BufferedReader进行了比较:
File file = new File ("C: \ \ file.txt");
FileReader fr = new FileReader (file);
BufferedReader br = new BufferedReader (fr);
...
String line = br.readLine (); BufferedReader读取一行并将其传递给字符串。
我可以看到这个java语句将文件内容传递给一个变量。
String line = br.readLine ();但我看不出另一种说法:
RandomAccessFile.read ();只要读一读,内容就不会在任何地方传递.
发布于 2014-03-13 11:18:39
你应该使用readFully
try (RandomAccessFile raf = new RandomAccessFile("filename", "r")) {
byte[] document = new byte[(int) raf.length()];
raf.readFully(document);
}编辑:你已经澄清了你的问题。您想知道为什么read不“返回”文件的内容。里面的东西是怎么到那里的?
答案是read没有分配任何内存来存储文件的内容。你是用new byte[length]做的。这是文件内容将去往的内存。然后调用read并告诉它将文件的内容存储在所创建的字节数组中。
BufferedReader.readLine不是这样操作的,因为只有它知道每一行需要读取多少字节,所以让您自己分配它们是没有意义的。
“如何”的快速例子:
class Test {
public static void main(String args[]) {
// here is where chars will be stored. If printed now, will show random junk
char[] buffer = new char[5];
// call our method. It does not "return" data.
// It puts data into an array we already created.
putCharsInMyBuffer(buffer);
// prints "hello", even though hello was never "returned"
System.out.println(buffer);
}
static void putCharsInMyBuffer(char[] buffer) {
buffer[0] = 'h';
buffer[1] = 'e';
buffer[2] = 'l';
buffer[3] = 'l';
buffer[4] = 'o';
}
}发布于 2014-03-13 10:48:43
randomAccessFile.read (document) ;此方法将读取no。文件中的字节,即文档数组长度的长度(如果文档数组的长度为1024字节),它将从文件中读取1024字节并放入数组中。
单击此处获取此方法的文档。
和
document = randomAccessFile.read () ;只要从文件中读取一个字节并返回它,它就不会读取整个文件。
单击此处获取此方法的文档。
https://stackoverflow.com/questions/22375924
复制相似问题