logo

Kako brati datoteko vrstico za vrstico v Javi

Obstajajo naslednji načini za branje datoteke vrstico za vrstico.

  • Razred BufferedReader
  • Razred optičnega bralnika

Uporaba razreda BufferedReader

Uporaba razreda Java BufferedRedaer je najpogostejši in preprost način za branje datoteke vrstico za vrstico v Javi. Pripada java.io paket. Razred Java BufferedReader ponuja metodo readLine() za branje datoteke vrstico za vrstico. Podpis metode je:

 public String readLine() throws IOException 

Metoda prebere vrstico besedila. Vrne niz, ki vsebuje vsebino vrstice. Vrstico je treba končati s pomikom vrstice (' ') ali vrnitvijo v začetek (' ').

Primer branja datoteke vrstico za vrstico z uporabo razreda BufferedReader

java ups koncepti

V naslednjem primeru Demo.txt bere razred FileReader. Metoda readLine() razreda BufferedReader bere datoteko vrstico za vrstico in vsako vrstico, dodano v StringBuffer, ki ji sledi začetek vrstice. Vsebina StringBufferja se nato izpiše na konzolo.

 import java.io.*; public class ReadLineByLineExample1 { public static void main(String args[]) { try { File file=new File('Demo.txt'); //creates a new file instance FileReader fr=new FileReader(file); //reads the file BufferedReader br=new BufferedReader(fr); //creates a buffering character input stream StringBuffer sb=new StringBuffer(); //constructs a string buffer with no characters String line; while((line=br.readLine())!=null) { sb.append(line); //appends line to string buffer sb.append('
'); //line feed } fr.close(); //closes the stream and release the resources System.out.println('Contents of File: '); System.out.println(sb.toString()); //returns a string that textually represents the object } catch(IOException e) { e.printStackTrace(); } } } 

Izhod:

Kako brati datoteko vrstico za vrstico v Javi

Uporaba razreda Scanner

Java Skener ponuja več uporabnih metod v primerjavi z razredom BufferedReader. Razred Java Scanner ponuja metodo nextLine() za omogočanje vrstice za vrstico vsebine datoteke. Metode nextLine() vrnejo isti niz kot metoda readLine(). Razred Scanner lahko bere tudi obliko datoteke InputStream.

Primer branja datoteke vrstico za vrstico z uporabo razreda Scanner

 import java.io.*; import java.util.Scanner; public class ReadLineByLineExample2 { public static void main(String args[]) { try { //the file to be opened for reading FileInputStream fis=new FileInputStream('Demo.txt'); Scanner sc=new Scanner(fis); //file to be scanned //returns true if there is another line to read while(sc.hasNextLine()) { System.out.println(sc.nextLine()); //returns the line that was skipped } sc.close(); //closes the scanner } catch(IOException e) { e.printStackTrace(); } } } 

Izhod:

Kako brati datoteko vrstico za vrstico v Javi