Zapis i odczyt danych tekstowych

 

Nowoczesna metoda odczytywania i zpisywania plików przy użyciu klasy Scanner.

Pokazany niżej program odczytuje zawartość pliku tekstowego znajdującego się na serwerze w internecie, a następnie wyświetla jego zawartość w konsoli i jednocześnie przepisuje kolejne wiersze pliku do pliku lokalnego.

import java.io.*;
import java.net.*;
import java.util.*;
import java.nio.charset.*;

public class IOScannerProgram {
	public static void main( String[] args ) throws FileNotFoundException, MalformedURLException, IOException {
		PrintWriter writer = new PrintWriter( "ioscannerprogramsample.txt" );
		try {
			URL url = new URL("http://aeropano.com/sample.txt");
			Scanner s = new Scanner( url.openStream(), "UTF-8" );

			String str=null;
			while( s.hasNext() ) { 
				str = s.nextLine();
				System.out.println( str );
				writer.println( str );
			}	
			
		} catch ( IOException e ) {
			System.out.println("BLAD ODZCZYTU LUB ZAPISU PLIKU.");
		} finally {
			writer.close();
		}


	}
}

 

 

Starsze metody zapisu i odczytu danych z pliku tekstowego:

 

Zapis

 

import java.io.FileNotFoundException;
import java.io.PrintWriter;
 
public class WriteTextToFile {
  public static void main( String[] args ) throws FileNotFoundException {
      PrintWriter writer = new PrintWriter( "sample.txt" );
      writer.println( "Spróbujmy z polskimi znakami ąśżźćńłóꥌƏŻŃÓŁĘ\nTo jest drugi wiersz lub \"zdanie\"." );
      writer.close();
  }
}

 

 

Odczyt

 

Prosta metoda wykorzystująca klasę Scanner:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
 
public class ReadTextFromFileWithScanner {
  public static void main( String[] args ) throws FileNotFoundException {
      File file = new File( "sample.txt" );
      Scanner in = new Scanner( file );    // String str = new Scanner( file, "utf-8" ).useDelimiter("\\Z").next();
 
      String sentence = in.nextLine();    // pobierz sekwencję znaków aż do napotkania \n - czyli całe zdanie
      System.out.println( sentence );
  }
}

 

Prosta - bardziej oldschoolowa metoda odczytująca tekst z pliku (dla uproszczenia bez uwzględnienia obsługi wyjątków):

public void readTextFromFile( String filePath ) throws IOException {
   FileReader fileReader = new FileReader( filePath );    // FileReader odczytuje kolejne znaki przy użyciu domyślnego kodowania; filePath - ścieżka do pliku w formie np. c:/plik.txt
   BufferedReader bufferedReader = new BufferedReader( fileReader );    // strumień danych mało wydajnego mechanizmu FileReader opakowujemy w wydajny strumień BufferedReader pozwalający na czytanie całych wierszy.
  
   String textLine = bufferedReader.readLine();    // metoda readLine() zwraca wiersz lub null, jeśli EOF
   while(textLine != null) {
       System.out.println( textLine );  
       textLine = bufferedReader.readLine();
   }

   bufferedReader.close();    // zwalniamy zasoby systemowe związane ze strumieniem
}

Ta sama metoda, lecz z bezpiecznym zamknięciem pliku - w bloku finally:

public void readTextFile( String filePath ) throws IOException {
  FileReader fileReader = new FileReader( filePath );
  BufferedReader bufferedReader = new BufferedReader( fileReader );
  
  try {
    String textLine = bufferedReader.readLine();
    do {
      System.out.println(textLine);
  
      textLine = bufferedReader.readLine();
    } while( textLine != null );
  } finally {
    bufferedReader.close();
  }
}

Odczyt przez internet - z serwera:

URL url = new URL( "http://aeropano.com/sample.txt" );
BufferedReader in = new BufferedReader( new InputStreamReader( url.openStream(), StandardCharsets.UTF_8 ) );
LinkedList<String> lines = new LinkedList();
String readLine;

while ((readLine = in.readLine()) != null) {
    lines.add(readLine);
}

for (String line : lines) {
    out.println("> " + line);
}