简体   繁体   中英

creating, writing to and reading from files java

I have made a program that is supposed to create a file, write to it, and then read from it. The problem comes with readFile(), where suddenly hasNext() is undefined for Formatter? I thought that

while (file.hasNext()) {
  String a = file.next(); 
  System.out.println(a);

would go as long as there was something in the file, copy it to a and then print a? What am I doing wrong?

import java.util.*;
import  java.io.*;

class Oppgave3
{
  public static void main(String[] args)
  {

    Kryptosystem a = new Kryptosystem();
    a.createFile();
    a.writeFile();
    a.openFile();
    a.readFile();
    a.closeFile();

  }
}

class Kryptosystem
{
  public Kryptosystem(){}

  Scanner keyboard = new Scanner (System.in);
  private Formatter file;
  private Scanner x;

  public void createFile(){
    try {
      file = new Formatter("kryptFil.txt");
    }
      catch (Exception e) {
      System.out.println("could not create file");
    }
  }

  public void writeFile(){
    System.out.println("what do you want to write");   
    String tekst = keyboard.nextLine();   
    file.format(tekst);
  }

  public void openFile() {
    try {
      x = new Scanner (new File("kryptFil.txt"));
    }
catch (Exception e) {
  System.out.println("something is wrong with the file");
}
}

  public void readFile() {
    while (file.hasNext()) {
      String a = x.next(); 
      System.out.println(a);
    }
  }

  public void closeFile() {
    file.close();
  }

    }

You state:

where suddenly hasNext() is undefined for Formatter?

Please have a look at the Formatter API as it will show you that this class has no hasNext() method, and your Java compiler is correctly telling you the same thing. Similarly, the Scanner API will show you that it in fact has the method you need.

You're opening the same File in a Scanner, called x , and this is what you want to use to read from the file. So the solution is to call hasNext() on the Scanner variable:

while (x.hasNext()) { // x, not file
  String a = x.next(); 
  System.out.println(a);
}

Note I'm not sure why you opened the file a second time and placed it into a Formatter object. Please clarify your motivation for this. I believe that you wish to write to the file with this, but you certainly would not try to use it to read from the File, which is what you're use of hasNext() is trying to do. I think you were just a little confused on which tool to use is all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM