需要你帮助的人。我的问题在于我的代码。虽然我使用的是RandomAccessFile但我在编写或读取文件时没有任何问题。但是如果我尝试使用带有BufferedInputStream的ObjectInputStream文件无法完全读取(只有第一个对象)。 这是我通过流或RandomAccessFile读取和写入的两种不同方式的代码
public static final String FNAME1 = "1.dat";
public static final String FNAME2 = "2.dat";
final static int ID_SIZE = 10;
final static int NAME_SIZE = 20;
final static int GRADE_SIZE = 5;
final static int RECORD_SIZE = (ID_SIZE + NAME_SIZE + GRADE_SIZE) * 2; // *2 because of the UNI-CODE.
private static Scanner s = new Scanner(System.in);
public static void main(String[] args){
int studNum;
System.out.println("Please enter how many students: ");
studNum=s.nextInt();
Student<?>[] a = new Student[studNum];
try{
createArrary(a,studNum);
save(a,FNAME1);
System.out.println("2.dat saved successfully!! \n");
fileCopy(FNAME1,FNAME2);
System.out.println("The Students in file: ");
read(FNAME2);
bubbleSort(FNAME1);
fileCopy(FNAME1,FNAME2);
System.out.println("2.dat after sorting:");
read(FNAME2);
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**Creates array of Students.*/
public static Student<?>[] createArrary(Student<?>[] a,int studNum) {
String input="";
for(int i = 0; i < studNum; i++) {
System.out.println("Student # "+(i+1)+":");
System.out.print("\nPlease enter the student's id: ");
int id = s.nextInt();
System.out.print("\nPlease enter Student's name : ");
s.nextLine();
String name = s.nextLine();
System.out.print("\nPlease enter Student's grade ");
input=s.nextLine();
if(isInteger(input)){
a[i]=new Student<>(id, name,Integer.parseInt(input));
}else{
a[i]=new Student<>(id,name,input);
}
}
return a;
}
/**Check if string has integer num.*/
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
return true;
}
/**Save Student array to the file.*/
public static void save(Student<?>[] a,String fileName) throws FileNotFoundException, IOException {
try (RandomAccessFile f = new RandomAccessFile(fileName, "rw")) {
f.setLength(0);
for (Student<?> p : a) {
writeFixedLengthString(String.valueOf(p.getId()),ID_SIZE,f);
writeFixedLengthString(p.getFullName(),NAME_SIZE,f);
writeFixedLengthString(String.valueOf(p.getGrade()),GRADE_SIZE,f);
}
}
}
public static void save(Student<?>[] a,String fileName) throws FileNotFoundException, IOException {
try(ObjectOutputStream o = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)))){
for(Student<?> p : a){
writeFixedLengthString(String.valueOf(p.getId()),ID_SIZE,o);
writeFixedLengthString(p.getFullName(),NAME_SIZE,o);
writeFixedLengthString(String.valueOf(p.getGrade()),GRADE_SIZE,o);
}
}
}
/**Read Students from file.*/
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException {
try (RandomAccessFile f = new RandomAccessFile(fileName, "r")) {
while (f.getFilePointer() < f.length()) {
int id=Integer.parseInt(readFixedLengthString(ID_SIZE,f));
String name=readFixedLengthString(NAME_SIZE,f);
String grade=readFixedLengthString(GRADE_SIZE,f);
System.out.println(new Student<>(id, name,grade));
}
}
}
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException {
BufferedInputStream f;
try(ObjectInputStream i = new ObjectInputStream(f = new BufferedInputStream(new FileInputStream(fileName)))){
while (f.available() > 0) {
int id=Integer.parseInt((readFixedLengthString(ID_SIZE,i)));
String name=readFixedLengthString(NAME_SIZE,i);
String grade=readFixedLengthString(GRADE_SIZE,i);
System.out.println(new Student<>(id, name,grade));
}
}
}
/** Write fixed number of characters to a DataOutput stream */
public static void writeFixedLengthString(String s, int size,
DataOutput out) throws IOException
{ char[] chars = new char[size];
s.getChars(0, Math.min(s.length(), size), chars, 0);
for (int i = s.length(); i < size; i++)
chars[i] = ' ';
out.writeChars(new String(chars));
}
/** Read fixed number of characters from a DataInput stream */
public static String readFixedLengthString(int size, DataInput in)
throws IOException
{ char[] chars = new char[size];
for (int i = 0; i < size; i++)
chars[i] = in.readChar();
return new String(chars).replaceAll(" ", "");
}
/** Copying source file to destination file */
public static void fileCopy(String fileSource,String fileDest) throws FileNotFoundException,IOException{
try(BufferedInputStream input=new BufferedInputStream(new FileInputStream(fileSource));BufferedOutputStream output =new BufferedOutputStream(new FileOutputStream(fileDest));){
int r;
while ((r = input.read()) != -1)
{ output.write(r);
}
}
}
/** Read Students from file and returns Object */
public static <T> Student<?> readSort(RandomAccessFile f) throws FileNotFoundException, IOException,NumberFormatException {
int id=Integer.parseInt(readFixedLengthString(ID_SIZE,f));
String name=readFixedLengthString(NAME_SIZE,f);
String grade=readFixedLengthString(GRADE_SIZE,f);
return new Student<>(id, name,grade);
}
/** Receive Student Objects and Save them to file */
public static <T> void saveSort(Student<T> stud,RandomAccessFile f) throws FileNotFoundException, IOException {
writeFixedLengthString(String.valueOf(stud.getId()),ID_SIZE,f);
writeFixedLengthString(stud.getFullName(),NAME_SIZE,f);
writeFixedLengthString(String.valueOf(stud.getGrade()),GRADE_SIZE,f);
}
/** Bubble Sort of Student's grades */
@SuppressWarnings("unchecked")
public static <T> void bubbleSort(String file) throws FileNotFoundException, IOException {
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
boolean needNextPass = true;
for (int k = 1; k < raf.length() / RECORD_SIZE && needNextPass; k++) {
needNextPass = false;
for (int i = 0; i < (raf.length() / RECORD_SIZE) - k; i++) {
raf.seek(RECORD_SIZE * i);
long tmpPrev = raf.getFilePointer();
Student<T> prevStud = (Student<T>) readSort(raf);
long tmpNext = raf.getFilePointer();
Student<T> nextStud = (Student<T>) readSort(raf);
if(isInteger((String) prevStud.getGrade())&&isInteger((String) nextStud.getGrade())){
if(Integer.parseInt((String) prevStud.getGrade())>Integer.parseInt((String) nextStud.getGrade())){
Student<T> temp=prevStud;
prevStud = nextStud;
nextStud = temp;
raf.seek(tmpPrev);
saveSort(prevStud, raf);
raf.seek(tmpNext);
saveSort(nextStud, raf);
needNextPass = true;
}
}else if(String.valueOf(prevStud.getGrade())
.compareTo(String.valueOf(nextStud.getGrade())) > 0 &&!isInteger((String) prevStud.getGrade())&&!isInteger((String) nextStud.getGrade())){
Student<T> temp=prevStud;
prevStud = nextStud;
nextStud = temp;
raf.seek(tmpPrev);
saveSort(prevStud, raf);
raf.seek(tmpNext);
saveSort(nextStud, raf);
needNextPass = true;
}else if(isInteger((String) prevStud.getGrade())&&!isInteger((String) nextStud.getGrade())||!isInteger((String) prevStud.getGrade())&&isInteger((String) nextStud.getGrade())&&String.valueOf(prevStud.getGrade())
.compareTo(String.valueOf(nextStud.getGrade())) < 0){
Student<T> temp=prevStud;
prevStud = nextStud;
nextStud = temp;
raf.seek(tmpPrev);
saveSort(prevStud, raf);
raf.seek(tmpNext);
saveSort(nextStud, raf);
needNextPass = true;
}
}
}
}
}
}
答案 0 :(得分:0)
好的我明白我可以这样写。
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException {
try(ObjectInputStream i = new ObjectInputStream(new BufferedInputStream(new FileInputStream(fileName)))){
while (i.available()>0) {
int id=Integer.parseInt((readFixedLengthString(ID_SIZE,i)));
String name=readFixedLengthString(NAME_SIZE,i);
String grade=readFixedLengthString(GRADE_SIZE,i);
System.out.println(new Student<>(id, name,grade));
}
}
}
但我如何将输入流转换为RandomAccessFile?