Я читаю файл с использованием метода readFully
класса RandomAccessFile
, но результаты не то, что я точно ожидал.Создание новой строки с использованием байтового массива дает странный результат
Это простая функция, которая считывает файл и возвращает 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!");
}
Выход: