Java: Read from a file
Read line by line using Scanner.
[code language=”java”]
public static void scannerReader(String filepath)
{
File text = new File(filepath);
Scanner scnr;
try {
scnr = new Scanner(text);
while(scnr.hasNextLine()){
String line = scnr.nextLine();
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
[/code]
Read line by line using FileInputStream, DataInputStream, InputStreamReader and BufferedReader.
[code language=”java”]
public static void streamReader(String filepath)
{
try{
FileInputStream fstream = new FileInputStream(filepath);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println (strLine);
}
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
[/code]
Read the entire file using InputStream.
[code language=”java”]
public static String readAll(String filepath)
{
File theFile = new File(filepath);
byte[] bytes = new byte[(int) theFile.length()];
InputStream in;
try {
in = new FileInputStream(theFile);
in.read(bytes);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return new String(bytes);
}
[/code]
All together.
[code language=”java”]
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
public class ReadLineFromFile {
public static void main(String args[])
{
String filepath="src/basics/files/AQuote.txt";
scannerReader(filepath);
streamReader(filepath);
System.out.println(readAll(filepath));
}
public static void scannerReader(String filepath)
{
File text = new File(filepath);
Scanner scnr;
try {
scnr = new Scanner(text);
while(scnr.hasNextLine()){
String line = scnr.nextLine();
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void streamReader(String filepath)
{
try{
FileInputStream fstream = new FileInputStream(filepath);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println (strLine);
}
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
public static String readAll(String filepath)
{
File theFile = new File(filepath);
byte[] bytes = new byte[(int) theFile.length()];
InputStream in;
try {
in = new FileInputStream(theFile);
in.read(bytes);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return new String(bytes);
}
}
[/code]
Search within Codexpedia

Search the entire web
