2

I have to write a code in JAVA like following structure:

Read String From File
// Perform some string processing
Write output string in file

Now, for reading/writing string to/from file, I am using,

BufferedReader br = new BufferedReader(new FileReader("Text.txt"), 32768);
BufferedWriter out = new BufferedWriter(new FileWriter("AnotherText.txt"), 32768);

  while((line = br.readLine()) != null) {
          //perform some string processing
          out.write(output string) ;
          out.newLine();
    }

However, it seems reading and writing is quite slow. Is there any other fastest method to read/write strings to/from a file in JAVA ?

Additional Info:

1) Read File is 144 MB.
2) I can allocate large memory (50 MB) for reading or writing.
3)I have to write it as a string, not as Byte.
15
  • How slow is "quite slow" exactly? Commented Apr 18, 2012 at 14:41
  • Is this homework? You should tag it as such. Commented Apr 18, 2012 at 14:42
  • 1
    What else are you doing apart from reading and writing? Do you have some transformations? Could that transformation be the expensive part? If you aren't transforming the data, why not just copy the file? Commented Apr 18, 2012 at 14:42
  • 4
    (As an aside, using FileWriter and FileReader is usually a bad idea, IMO. I prefer using FileOutputStream and FileInputStream, wrapped in an OutputStreamWriter or InputStreamReader, and explicitly specifying the character encoding (typically UTF-8). Otherwise it will always use the platform default encoding, making your file less-than-ideally-portable...) Commented Apr 18, 2012 at 14:47
  • 1
    If you get rid of the String processing & just write back out what you read in, what does your performance look like? Commented Apr 18, 2012 at 15:00

2 Answers 2

1

It sounds slower than it should be.

You can try increasing the buffer size.

Maybe also try FileOutputStream instead of FileWriter.

You mentioned 50MB. Are you modifying the memory parameters of the program at all when you run it using a -X switch?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I try for 32 KB, 64 KB. However, same time. In one discussion, in SO, it is told to me 32 KB is more or less optimal one. However, is NIO can be a better one ?
0

Ignoring the fact that you have not posted what your performance requirements are:

Try reading/writing the file as bytes and internally convert the byte to characters/string.

This question might be helpful: Number of lines in a file in Java

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.