Skip to content

Instantly share code, notes, and snippets.

@gansai
Created November 12, 2015 17:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save gansai/c4b2325cc4846e24ded3 to your computer and use it in GitHub Desktop.
Reading a text file in Java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* Created by gansai on 12/11/15.
* Referred to http://stackoverflow.com/a/4716623
*/
public class ReadFile {
public static void main(String args[]) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("D:\\file.txt"));
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();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br!=null)
{
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment