我正在将值写入到文件中。
这些值写得正确。在另一个应用程序中,我可以毫无例外地读取该文件。
但是在我的新应用程序中,当我试图读取文件时,我得到了一个Bufferunderflowexception。
bufferunderflowexception指的是:
Double X1 = mappedByteBufferOut.getDouble(); //8 byte (double)这是我读取文件的代码:
@Override
public void paintComponent(Graphics g) {
RandomAccessFile randomAccessFile = null;
MappedByteBuffer mappedByteBufferOut = null;
FileChannel fileChannel = null;
try {
super.paintComponent(g);
File file = new File("/home/user/Desktop/File");
randomAccessFile = new RandomAccessFile(file, "r");
fileChannel = randomAccessFile.getChannel();
mappedByteBufferOut = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());
while (mappedByteBufferOut.hasRemaining()) {
Double X1 = mappedByteBufferOut.getDouble(); //8 byte (double)
Double Y1 = mappedByteBufferOut.getDouble();
Double X2 = mappedByteBufferOut.getDouble();
Double Y2 = mappedByteBufferOut.getDouble();
int colorRGB = mappedByteBufferOut.getInt(); //4 byte (int)
Color c = new Color(colorRGB);
Edge edge = new Edge(X1, Y1, X2, Y2, c);
listEdges.add(edge);
}
repaint();
for (Edge ed : listEdges) {
g.setColor(ed.color);
ed = KochFrame.edgeAfterZoomAndDrag(ed);
g.drawLine((int) ed.X1, (int) ed.Y1, (int) ed.X2, (int) ed.Y2);
}
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
finally
{
try
{
mappedByteBufferOut.force();
fileChannel.close();
randomAccessFile.close();
listEdges.clear();
} catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
}发布于 2013-12-18 05:09:07
来自java.nio.ByteBuffer的docs:
抛出: BufferUnderflowException -如果此缓冲区中剩余的字节少于8个字节
我认为这很清楚这个异常是从哪里来的。为了修复它,您需要确保ByteBuffer中有足够的数据,以便通过检查remaining()而不是只检查一个字节的hasRemaining()来读取双精度值(8字节):
while (mappedByteBufferOut.remaining() >= 36) {//36 = 4 * 8(double) + 1 * 4(int)发布于 2013-12-18 05:02:08
如果可以使用double,我就不会使用Double
我怀疑您的问题是在循环开始时还有剩余的字节,但是您没有检查有多少字节,所以没有足够的字节。
我也会确保你有正确的字节顺序,默认的是高字节顺序。
https://stackoverflow.com/questions/20644505
复制相似问题