2014-08-31 55 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。

简答:字节不是字符

相关问题