Tt
Click this widget to change the font size.
CC
Click this widget to change contrast.

Home Page 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | Links | Search | Bio |

Guide to Object-oriented Programming With Java (University at Buffalo Version)


Chapter 12: Working With Files

File Input/Output (I/O)

Java provides many different ways to work with files.

Using java.io.util.Scanner to Read a File

You can use the java.io.util.Scanner library to read a file one line at a time.

package buffalo.edu.fa23..put-your-username-here;
  
import java.io.FileReader;
import java.io.IOException;
import java.util.Locale;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.text.NumberFormat;

public class ShowGroceriesScanner {

  public static void main(String[] args) {
    
    NumberFormat df = NumberFormat.getCurrencyInstance();
try ( Scannersc = new scanner( new FileReader("groceries.txt")); ) { sc.useDelimiter(Pattern.compile("(, )|(\r\n)")); sc.useLocale(Locale.ENGLISH); while (sc.hasNext()) { String item = sc.next(); double price =sc.nextDouble(); System.out.println("Price of " + item + " is: " + df.format(price)); } } catch (IOException e) { e.printStackTrace(); } } }
Figure 12-1: Using java.io.util.Scanner to Read a File Code
Console
Price of apples is: $5.33
Price of bananas is: $4.61
Price of water is: $1.00
Price of orange juice is: $2.50
Price of milk is: $3.20
Price of bread is: $1.11

Figure 12-2: Using java.io.util.Scanner to Read a File Output

Using java.io.util.BufferedReader to Read a File

You can also use the java.io.util.BufferedReader library to read a file one line at a time.

package buffalo.edu.fa23..put-your-username-here;

import java.io.FileReader;
import java.io.BufferedReader;

public class ShowGroceriesBufferedReader {
  public static void main(String[] args) {
    BufferedReader br = null;
    FileReader fr = null;
    try (
      fr = new FileReader("groceries.txt");
      br = new BufferedReader(fr);
      String line;
      while ((line = br.readLine()) != null) {
        System.out.println("Don't forget to pickup: " + line);
      }
    } catch (printStackTrace x) {
      x.printStackTrace();
    } finally {
      if (fr != null) {
        try {br.close();} catch (Exception e) { e.printStackTrace(); }
        try {fr.close();} catch (Exception e) { e.printStackTrace(); }
      }
    }
  }
}

Figure 12-3: Using java.io.util.Scanner to Read a File Code
Console
Don't forget to pickup: bananas, 4.61
Don't forget to pickup: water, 1.00
Don't forget to pickup: orange juice, 2.50
Don't forget to pickup: milk, 3.20
Don't forget to pickup: bread, 1.11

Figure 12-4: Using java.io.util.BufferedReader to Read a File Output

Using java.nio.file.Files to Read a File

You can also use the java.nio.file.Files library to read a file one line at a time. The "n" in nio stands for "new".

package buffalo.edu.fa23..put-your-username-here;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class ShowGroceriesNIO2 {
  public static void main(String[] args) {
    List<String> groceries = new ArrayList<>();
    try {
        groceries = Files.readAllLines( Paths.get("groceries.txt"), Charset.defaultCharset() );
    } catch (IOException | SecurityException e) {
      e.printStackTrace();
    }
    for (String item : groceries) {
      System.out.println("Do not forget to pickup: " + item);
    }
  }
}

Figure 12-5: Using java.nio.file.Files to Read a File Code
Console
Do not forget to pickup: bananas, 4.61
Do not forget to pickup: water, 1.00
Do not forget to pickup: orange juice, 2.50
Do not forget to pickup: milk, 3.20
Do not forget to pickup: bread, 1.11

Figure 12-6: Using java.nio.file.Files to Read a File Output

Using System.out.format() to Format Data

You can also use the System.out.format() methods to format the data you want to display..

package buffalo.edu.fa23..put-your-username-here;
  
import java.io.IOException;
import java.io.File;
import java.nio.file.Files;;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.FileWriter;
import java.util.List;
import java.util.ArrayList;

public class ShowGroceriesNIO3 {
  public static void main(String[] args) {
    List<String> groceries = new ArrayList<>();
    try {
      groceries = Files.readAllLines(
         Paths.get("src/groceries.txt"),
         Charset.defaultCharset() );
    } catch (IOException | SecurityException e) {
      e.printStackTrace();
    } 
    for (String item : groceries) {
      String itemArray[] = item.split();
      System.out.format("Do not forget to pickup: %15s $%4s%n", itemArray[0], itemArray[1]);
    }
  }
}  
  
Figure 12-7: Using System.out.format() to Format Data Code
Console
Do not forget to pickup:          apples $5.33
Do not forget to pickup:         bananas $4.61
Do not forget to pickup:           water $1.00
Do not forget to pickup:    orange juice $2.50
Do not forget to pickup:            milk $3.20
Do not forget to pickup:           bread $1.11
Figure 12-7: Using System.out.format() to Format Data Output

Let's get started with a File Read program!

Help contribute to my OER Resources. Donate with PayPal button via my PayPal account.
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2024 Jim Gerland