我正在使用类的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!");
}
输出: