簡體   English   中英

RandomAccessFile類如何使用randomAccessFile.read()方法返回字節;

[英]How the RandomAccessFile class returns bytes with randomAccessFile.read() method;

我正在使用google翻譯器,希望這個問題能很好理解。

我不了解隨機訪問文件是一件事。不了解該程序如何工作,但是它可以工作。

這是我的程序:

// ---------------------------------------------
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 ) .

僅返回字節數,而不返回字節數。

有人可以向我解釋這一行如何使用此語句轉儲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 ();

剛讀,內容不會在任何地方通過該行...

您應該使用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';
    }
}
randomAccessFile.read (document) ;

此方法將讀取編號。 文件中的字節數,即文檔數組的長度。如果文檔數組的長度為1024字節,它將從文件中讀取1024字節並將其放入數組中。

單擊此處以獲取此方法的文檔

document = randomAccessFile.read () ;

只會從文件中讀取一個字節並返回它,而不會讀取整個文件。

單擊此處獲取此方法的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM