메서드를 사용하여 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();
}
}
나는이 쓰기 방법을 사용하여 파일에 기록 :