3

I store over 40,000 objects into a text file. My problem is reading all objects from text file is too slow. It even takes 4349 ms for 1,000 objects-text file.

This is reading objects from text file.

long startR = System.currentTimeMillis();

try{
    ois = new ObjectInputStream(new FileInputStream(f));
    code_from_file.clear();
    Codes obj = new Codes();

    while( (obj = (Codes) ois.readObject()) != null){   
        if(obj instanceof Codes){
            code_from_file.add(obj);
        }
    }

}catch (EOFException ex){ 

} catch (ClassNotFoundException ex) {
    ex.printStackTrace();
} catch (FileNotFoundException ex) {
    ex.printStackTrace();
} catch (IOException ex) {
    ex.printStackTrace();
} finally{
    try {
        if (ois != null){
            ois.close();
        }
    } catch (IOException ex){
        ex.printStackTrace();
    }
}

long endR = System.currentTimeMillis();
System.out.println("Read code from file : " + (endR - startR) + "ms");  

Is there any faster way for solving this problem?

Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
Yu Wai Hlaing
  • 141
  • 1
  • 10

2 Answers2

1

An easy optimization to try would be to add buffering to your input stream processing. As you wrote it, each read may be hitting your disk. If you do fewer physical reads (in larger chunks), you may see a performance improvement.

int bufferSize = 16 * 1024;
ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(f), bufferSize));

When bytes are read via the ObjectInputStream, they are actually being read in memory from the BufferedInputStream's buffer. When this buffer becomes empty (has all been read), the BufferedInputStream will re-fill the buffer in one large read from the FileInputStream.

You can experiment with different buffer sizes to determine an appropriate balance between the number of I/O operations vs. the memory overhead.

Rob
  • 6,247
  • 2
  • 25
  • 33
1

Try using NIO, it has many enhancements and buffering

    RandomAccessFile aFile = new RandomAccessFile("test.txt", "r");
    FileChannel inChannel = aFile.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    int read;
    while((read = inChannel.read(buffer)) != -1){
        os.write(buffer, 0, read);
    }
    inChannel.close();
    aFile.close();

above code is with the fixed width of buffer size

Saravana
  • 12,647
  • 2
  • 39
  • 57