Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I am quite new to java, and I am trying to read a file into a string (or should I use byte arrays for this?). File can be anything, it can be a text file or executable file etc. I will compress what I read and write it to another file. I am thinking of using this code;

public static String readFile(File f) {
    StringBuilder sb = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new FileReader(f))) {
        String sCurrentLine;
        while ((sCurrentLine = br.readLine()) != null) {
            sb.append(sCurrentLine);
        }

    } catch (IOException e) {
        System.err.println("I/O Exception:" + e.getMessage());
        return null;
    }
    return sb.toString();
}

Does this look good to you? I was reading Reading and writing text files and I was a little bit confused over all the different ways one can use to read files.

share|improve this question
 
I would suggest that you read this : stackoverflow.com/questions/3402735/… –  tomdemuyt Aug 8 at 17:42
2  
Strings are for character data only. Since the file might be an executable, that means it's not always going to be valid character data, so yes, you should use byte arrays instead of strings. –  Matt Ball Aug 8 at 19:33

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.