2

我正在使用谷歌翻译,我希望这个问题很好理解。

有一件事我不了解随机访问文件。不了解程序是如何工作的,但它可以工作。

这是我的程序:

// ---------------------------------------------
RandomAccessFile RandomAccessFile = new RandomAccessFile ( " pathfile ", " r");

byte [] document = new byte [ ( int) randomAccessFile.length ()] ;

randomAccessFile.read (document) ;
// ---------------------------------------------

在第 1 行中,我在 read 中访问文件 在第 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 ) .

只返回字节数而不是字节数。

有人可以向我解释这一行如何使用此语句转储 byte [] 变量文档中的字节?

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 ();

刚刚阅读,内容不会在任何地方通过该行...

4

2 回答 2

5

你应该使用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-13T11:18:39.273 回答
1
randomAccessFile.read (document) ;

此方法将读取编号。文件中的字节数,即文档数组长度的长度 如果文档数组的长度为 1024 字节,它将从文件中读取 1024 字节并将其放入数组中。

单击此处获取此方法的文档

document = randomAccessFile.read () ;

只会从文件中读取一个字节并返回它,它不会读取您的整个文件。

单击此处获取此方法的文档

于 2014-03-13T10:48:43.257 回答