我正在尝试从文本文件创建数据段,以通过网络传输到另一台设备,但我的阅读器无法正常工作。
它将读取该块,发送它并更新计数器值
remainigBytes
,然后从下一个段应该开始的位置读取下一个段。例如,HelloWorld 将是“Hello”和“World”的 2 个 5 字节段,但是当我读取文件时,它只读取前 5 个字母(“Hello”)2 次,根本不读取“World”。
如何让 fileReader 从特定的起点而不是总是从头开始读取。如果我可以实现更合适的阅读器,我不受使用 FileReader 的限制,请告诉我。
public int readData() throws IOException {
//creates the file reader for the input file.
FileReader myReader = null;
try {
myReader = new FileReader(inputFileName);
} catch (IOException e){
System.out.println("File reader could not be initialized");
System.out.println(e.getMessage());
System.exit(0);
}
System.out.println("Creating segment...");
System.out.println("----------------------------------------------------");
//reads the input file and changes the segments values
if (this.remainingBytes < this.maxPayload) {
//if the payload size is greater than the number of characters left
char[] segCharsBuf = new char[(int) this.remainingBytes];
myReader.read(segCharsBuf,0,(int)this.remainingBytes);
this.dataSeg.setSize((int)remainingBytes);
this.dataSeg.setPayLoad(Arrays.toString(segCharsBuf));
this.dataSeg.setSq(((int)this.fileSize - (int)this.remainingBytes) / this.maxPayload);
System.out.println("Segment number " + this.dataSeg.getSq() +" created (" + this.dataSeg.getSize() + " Bytes)");
System.out.println("----------------------------------------------------");
return -1;
} else {
//if the file is longer or just as ling as the payload size
char[] segCharsBuf = new char[this.maxPayload];
myReader.read(segCharsBuf,0, this.maxPayload);
this.dataSeg.setSize(this.maxPayload);
this.dataSeg.setPayLoad(Arrays.toString(segCharsBuf));
this.dataSeg.setSq(((int)this.fileSize - (int)this.remainingBytes) / this.maxPayload);
System.out.println("Segment number " + this.dataSeg.getSq() +" created (" + this.dataSeg.getSize() + " Bytes)");
System.out.println("----------------------------------------------------");
return 0;
}
}
每次调用
readData
时,您都会创建一个新的 FileReader
对象,该对象将从头开始读取文件。相反,您应该在数据成员中保留相同的读取器,并在每次调用 readData
时继续读取数据。