簡體   English   中英

從文件Java讀取字節

[英]Read bytes from file Java

我正在嘗試解析我的文件,該文件將所有數據保留為二進制形式。 如何從偏移量為M的文件中讀取N個字節? 然后,我需要使用new String(myByteArray, "UTF-8");將其轉換為String new String(myByteArray, "UTF-8"); 謝謝!

這是一些代碼:

File file = new File("my_file.txt");
byte [] myByteArray = new byte [file.lenght];

UPD 1:我看到的答案不恰當。 我的文件以字節形式保留字符串,例如:當我在文件中放入字符串“ str”時,它實際上在文件中打印出類似[B @ 6e0b ...]的內容。 因此,我需要再次從該字節碼中獲取字符串“ str”。

UPD 2:據發現,當我使用toString()時出現了問題:

    PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(System.getProperty("db.file")), true), "UTF-8")));
    Iterator it = storage.entrySet().iterator();//storage is a map<String, String>
    while (it.hasNext()){
        Map.Entry pairs = (Map.Entry)it.next();
        String K = new String(pairs.getKey().toString());
        String V = new String(pairs.getValue().toString);
        writer.println(K.length() + " " + K.getBytes() + " " + V.length() + " " + V.getBytes());//this is just the format I need to have in file
        it.remove();
    }   

可能有幾種不同的方法可以執行此操作?

從Java 7開始,讀取整個文件非常容易-只需使用Files.readAllBytes(path) 例如:

Path path = Paths.get("my_file.txt");
byte[] data = Files.readAllBytes(path);

如果您需要更手動地執行此操作,則應使用FileInputStream到目前為止,您的代碼分配了一個數組,但未從文件中讀取任何內容。

要僅讀取文件的一部分 ,應該使用RandomAccessFile查看,它使您可以查找所需的任何位置。 請注意, read(byte[])方法不能保證一次性讀取所有請求的數據。 您應該循環播放,直到您已經閱讀了所需的所有內容,或者改為使用readFully 例如:

public static byte[] readPortion(File file, int offset, int length)
    throws IOException {
  byte[] data = new byte[length];
  try (RandomAccessFile raf = new RandomAccessFile(file)) {
    raf.seek(offset);
    raf.readFully(data);
  }
  return data;
}

編輯:您的更新談論看到諸如[B@6e0b.. 這表明您有時會在byte[]上調用toString() 不要那樣做 相反,您應該使用new String(data, StandardCharsets.UTF_8)或類似的名稱-當然選擇合適的編碼。

暫無
暫無

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

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