[英]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.