RandomAccessFile 클래스를 사용하려고하지만 문자열에 문제가 있습니다.Endline StringBuilder in RandomAccessFile
이것은 첫 번째 부분입니다. 내가 읽은 희망하는 경우는,
File file = new File("/home/pep/java/randomFile.dat");
RandomAccessFile randomFile = new RandomAccessFile(file, "r");
char[] surname = new char[10];
char aux;
int id, dep, pos;
Double salary;
pos = 0;
for (;;) {
randomFile.seek(pos);
id = randomFile.readInt();
for (int i = 0; i < surname.length; i++) {
aux = randomFile.readChar();
surname[i] = aux;
}
String surnameStr = new String(surname); //HERE IS THE PROBLEM!!
dep = randomFile.readInt();
salary = randomFile.readDouble();
System.out.println("ID: " + id + ", Surname: " + surnameStr + ", Departament: " + dep + ", Salary: " + salary);
pos = pos + 36; // 4 + 20 + 4 + 8
if (randomFile.getFilePointer() == randomFile.length())
break;
}
randomFile.close();
}
음 :
ID : 1, 성을 : 파일에 쓰기 :
public static void main(String[] args) throws IOException { File file = new File("/home/pep/java/randomFile.dat"); RandomAccessFile fitxerAleatori = new RandomAccessFile(file, "rw"); String[] surnames = { "SMITH", "LOMU" }; int[] dep = { 10, 20 }; Double[] salary = { 1200.50, 1200.50 }; StringBuilder buffer = null; int n = surnames.length; for (int i = 0; i<n; i++){ randomFile.writeInt(i+1); //ID buffer = new StringBuilder(surnames[i]); buffer.setLength(10); //10 characters randomFile.writeChars(buffer.toString()); randomFile.writeInt(dep[i]); randomFile.writeDouble(salary[i]); } randomFile.close(); }
을 두 번째 부분에서,이 파일을 읽어보십시오 SMITH , 출발지 : 10 급여 : 1200.50
내가 recived :
ID : 1, 성 : SMITH
그것은 내가이 성을 표시하지 않는 경우, 다른 정보가 정확하기 때문에, 라인의 끝이 성에서 같다.
감사합니다.
문제는 데이터 자체에 있습니다. 10 자 미만의 문자열을 처리하는 방법에 대해서는 사용자가 동의하지 않았습니다. – EJP