2014-08-31 4 views
0

메서드를 사용하여 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(); 
    } 
} 

나는이 쓰기 방법을 사용하여 파일에 기록 : enter image description here

답변

1

내가 writeChars 방법을 사용 : 출력이

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!"); 
} 

.

모든 문자를 기본 인코딩이 아닌 UTF-16으로 작성합니다. UTF-16BE 문자 인코딩을 사용하면 문자를 디코딩합니다. UTF_16은 문자 당 2 바이트를 사용합니다.

(char) 0(char) 255 사이의 문자 만 필요한 경우 크기가 절반이므로 ISO-8859-1 인코딩을 사용하는 것이 좋습니다.

0

문제는 사용자가 Charset을 지정하지 않고 "플랫폼 기본값"이 사용되고 있다는 것입니다. 이것은 거의 항상 나쁜 생각입니다. 대신 this constructor: String(byte[], Charset)을 사용하고 파일이 작성된 인코딩을 명시해야합니다. 주어진 출력을 볼 때 2 바이트 인코딩 인 UTF-16BE 인 것으로 보입니다.

짧은 대답 : 바이트 수는 문자가 아닙니다

관련 문제