簡體   English   中英

使用字節數組創建新的字符串會產生奇怪的結果

[英]Creating a new String using a byte array is giving a strange result

我正在使用RandomAccessFile類的readFully方法讀取文件,但結果並非我確切預期的。

這是簡單的函數,它讀取文件並使用存儲所有字節的字節數組返回new String

public String read(int start)
{
    setFilePointer(start);//Sets the file pointer

    byte[] bytes = new byte[(int) (_file.length() - start)];

    try
    {
        _randomStream.readFully(bytes);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

    return new String(bytes);
}

在主要方面:

public static void main(String[] args)
{
    String newline = System.getProperty("line.separator");

    String filePath = "C:/users/userZ/Desktop/myFile.txt";
    RandomFileManager rfmanager = new RandomFileManager(filePath, FileOpeningMode.READ_WRITE);

    String content = rfmanager.read(10);

    System.out.println("\n"+content);

    rfmanager.closeFile();
}

RandomFileManager的構造函數中調用此函數。 如果文件尚不存在,它將創建文件。

private void setRandomFile(String filePath, String mode)
{
    try
    {
        _file = new File(filePath);

        if(!_file.exists())
        {

            _file.createNewFile();// Throws IOException
            System.out.printf("New file created.");
        }
        else System.out.printf("A file already exists with that name.");

        _randomStream = new RandomAccessFile(_file, mode);

    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
}

我使用以下寫入方法寫入文件:

public void write(String text)
{
    //You can also write
    if(_mode == FileOpeningMode.READ_WRITE)
    {
        try
        {
            _randomStream.writeChars(text);
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
    else System.out.printf("%s", "Warning!");
}

輸出: 在此處輸入圖片說明

我使用了writeChars方法。

這會將所有字符寫為UTF-16,這不太可能是默認編碼。 如果使用UTF-16BE字符編碼,則將解碼字符。 UTF_16每個字符使用兩個字節。

如果您只需要介於(char) 0(char) 255之間的(char) 0 ,我建議使用ISO-8859-1編碼,因為它的大小為一半。

問題是您沒有指定字符集,因此正在使用“平台默認值”。 這幾乎總是一個壞主意。 而是使用以下構造函數:String(byte [],Charset)並明確說明編寫文件時使用的編碼。 給定您顯示的輸出,它似乎是兩字節編碼,可能是UTF-16BE。

簡短答案:字節不是字符

暫無
暫無

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

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