2014-08-31 16 views
0

我正在使用類的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!"); 
} 

輸出: enter image description here

回答

1

我用writeChars方法。

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

如果你只需要(char) 0(char) 255之間的字符,我建議使用ISO-8859-1編碼,因爲它將是一半尺寸。

0

問題是你沒有指定一個字符集,所以正在使用「平臺默認」。這幾乎總是一個壞主意。相反,使用this constructor: String(byte[], Charset)並明確說明該文件的編碼。鑑於您所展示的輸出,它似乎是一個雙字節編碼,可能是UTF-16BE。

簡答:字節不是字符

相關問題