0

I've been looking around on the Internet trying to figure out which could be the best way to read from text files which are not very long (the use case here involves small OpenGL shaders). I ended up with this:

private static String load(final String path)
{
    String text = null;

    try
    {
        final FileReader fileReader = new FileReader(path);
        fileReader.read(CharBuffer.wrap(text));

        // ...
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

    return text;
}

In which cases could this chunk of code result in inefficiencies? Is that CharBuffer.wrap(text) a good thing?

pr0gma
  • 577
  • 3
  • 8
  • 18

2 Answers2

1

I would usually just roll like this. The CharBuffer.wrap(text) thing seems to only get you a single character ... File Reader docs

BufferedReader br = new BufferedReader(fr); 
StringBuilder sb = new StringBuilder();
String s; 
while((s = br.readLine()) != null) { 
   sb.append(s);
} 
fr.close(); 
return sb.toString();
fergdev
  • 963
  • 1
  • 13
  • 27
1

If you want to read the file line by line:

BufferedReader br = new BufferedReader(new FileReader(path));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
} finally {
    br.close();
}

If you want to read the complete file in one go:

String text=new String(Files.readAllBytes(...)) or Files.readAllLines(...)

Abhishek Garg
  • 2,158
  • 1
  • 16
  • 30
  • How does the last method you mentioned behave in terms of efficiency when dealing with small files (say less than 50 lines, less than 50 chars per line)? I know this is a very broad question but still I'm interested in the answer. – pr0gma Feb 11 '16 at 19:14
  • 1
    http://ideone.com/JD5FS6 Time taken to read using bufferedReader 1 Time taken to read using readallBytes 11 Actually BufferedReader is around 10 times more efficient than ReadAllBytes for a file that you have mentioned. Use BufferedReader for this. – Abhishek Garg Feb 11 '16 at 19:37
  • That's [not an appropriate way to benchmark a Java program](http://stackoverflow.com/a/513259/4125191). – RealSkeptic Feb 12 '16 at 07:11