Java 使用字节数组创建新字符串会产生奇怪的结果
我正在使用Java 使用字节数组创建新字符串会产生奇怪的结果,java,file-io,randomaccessfile,Java,File Io,Randomaccessfile,我正在使用RandomAccessFile类的readFully方法读取一个文件,但结果并不是我所期望的 这是一个简单的函数,它读取文件并使用存储所有字节的字节数组返回一个新字符串: public String read(int start) { setFilePointer(start);//Sets the file pointer byte[] bytes = new byte[(int) (_file.length() - start)]; try {
RandomAccessFile
类的readFully
方法读取一个文件,但结果并不是我所期望的
这是一个简单的函数,它读取文件并使用存储所有字节的字节数组返回一个新字符串
:
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
之间的字符,我建议使用ISO-8859-1编码,因为它将是大小的一半。问题在于您没有指定字符集,因此使用了“平台默认值”。这几乎总是个坏主意。相反,使用并明确说明文件编写时使用的编码。鉴于您正在显示的输出,它似乎是一种双字节编码,很可能是UTF-16BE
简短回答:字节不是字符