Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 80597
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T21:19:39+00:00 2026-05-10T21:19:39+00:00

I’ve been using the idiom below for some time now. And it seems to

  • 0

I’ve been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I’ve visited.

Is there a better/different way to read a file into a string in Java?

private String readFile(String file) throws IOException {     BufferedReader reader = new BufferedReader(new FileReader (file));     String line = null;     StringBuilder stringBuilder = new StringBuilder();     String ls = System.getProperty("line.separator");      try {         while((line = reader.readLine()) != null) {             stringBuilder.append(line);             stringBuilder.append(ls);         }          return stringBuilder.toString();     } finally {         reader.close();     } } 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T21:19:40+00:00Added an answer on May 10, 2026 at 9:19 pm

    Read all text from a file

    Java 11 added the readString() method to read small files as a String, preserving line terminators:

    String content = Files.readString(path, encoding); 

    For versions between Java 7 and 11, here’s a compact, robust idiom, wrapped up in a utility method:

    static String readFile(String path, Charset encoding)   throws IOException {   byte[] encoded = Files.readAllBytes(Paths.get(path));   return new String(encoded, encoding); } 

    Read lines of text from a file

    Java 7 added a convenience method to read a file as lines of text, represented as a List<String>. This approach is "lossy" because the line separators are stripped from the end of each line.

    List<String> lines = Files.readAllLines(Paths.get(path), encoding); 

    Java 8 added the Files.lines() method to produce a Stream<String>. Again, this method is lossy because line separators are stripped. If an IOException is encountered while reading the file, it is wrapped in an UncheckedIOException, since Stream doesn’t accept lambdas that throw checked exceptions.

    try (Stream<String> lines = Files.lines(path, encoding)) {   lines.forEach(System.out::println); } 

    This Stream does need a close() call; this is poorly documented on the API, and I suspect many people don’t even notice Stream has a close() method. Be sure to use an ARM-block as shown.

    If you are working with a source other than a file, you can use the lines() method in BufferedReader instead.

    Memory utilization

    If your file is small enough relative to your available memory, reading the entire file at once might work fine. However, if your file is too large, reading one line at a time, processing it, and then discarding it before moving on to the next could be a better approach. Stream processing in this way can eliminate the total file size as a factor in your memory requirement.

    Character encoding

    One thing that is missing from the sample in the original post is the character encoding. This encoding generally can’t be determined from the file itself, and requires meta-data such as an HTTP header to convey this important information.

    The StandardCharsets class defines some constants for the encodings required of all Java runtimes:

    String content = readFile("test.txt", StandardCharsets.UTF_8); 

    The platform default is available from the Charset class itself:

    String content = readFile("test.txt", Charset.defaultCharset()); 

    There are some special cases where the platform default is what you want, but they are rare. You should be able justify your choice, because the platform default is not portable. One example where it might be correct is when reading standard input or writing standard output.


    Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 61k
  • Answers 61k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • added an answer .o files are objects. They are the output of the… May 11, 2026 at 9:53 am
  • added an answer Everything you have looks pretty standard - the only thing… May 11, 2026 at 9:53 am
  • added an answer This is a perfectly normal practice. Performance wise, I don't… May 11, 2026 at 9:53 am

Related Questions

I keep getting tasks that are above my skill level. How can I address this without coming accross as grossly incompetent?
I have a web-service that I will be deploying to dev, staging and production.
I'm thinking of starting a wiki, probably on a low cost LAMP hosting account.
I have the following tables in my database that have a many-to-many relationship, which
I'm using the RESTful authentication Rails plugin for an app I'm developing. I'm having
I recently printed out Jeff Atwood's Understanding The Hardware blog post and plan on
I find that getting Unicode support in my cross-platform apps a real pain in
I would like to test a string containing a path to a file for
I'm getting this problem: PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable
I'm an Information Architect and JavaScript developer by trade nowadays, but recently I've been

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.