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