Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Chapter 6 Java IO File

845 views

Published on

Chapter 6 Java IO File

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Chapter 6 Java IO File

  1. 1. CHAPTER 6 READING AND WRITING TEXT FILE
  2. 2. Writing Data using PrintWriter • The java.io.PrintWriter class can be used to write data to a text file. PrintWriter output = new PrintWriter(filename) • Then you can invoke the print, println and printf methods on the PrintWriter object to write data to a file.
  3. 3. … Writing Text File import java.io.*; public class WriteData { public static void main (String args[]) throws Exception{ java.io.File file = new java.io.File(“scores.txt”); if (file.exists()){ System.out.println(“File already exists”); System.exit(0); } //create file java.io.PrintWriter output = new java.io.PrintWriter(file); output.print(“John T Smith); output.print(90); output.print(“Eric K Jones”); output.print(85); //close file output.close(); } } }
  4. 4. … Writing Text File • Output from file.txt – can be opened from any text editor. John T Smith 90 Eric K Jones 85
  5. 5. Reading Data using Scanner • As in example 
  6. 6. import java.util.Scanner; public class File { public static void main (String args[]) throws Exception{ java.io.File file = new java.io.File(“scores.txt”); Scanner input = new Scanner (file); while(input.hasNext(){ String firstName=input.next(); String mi=input.next(); String lastName=input.next(); int score=input.nextInt(); S.O.P(firstName+ “”+mi+ “”+lastName+ “”+score); } //close file input.close(); } }
  7. 7. … Reading Text File • Output produced: John T Smith 90 Eric K Jones 85

×