-3

I have created a class that has the features of reading and writing to a file even parsing what is in the file. But when I run my test, I am not able to read the file. This is the snippet of what I have, if it is not enough I can post the rest of what I have to help.

this is what my main looks like:

public static void main(String args[]) throws IOException {

    String fileLocation = File.separator + "Users" + File.separator + "Desktop" + File.separator + "test.txt";
File file = new File(fileLocation);

DataStorage data = new DataStorage(fileLocation);
data.read();
}

this is what my read method looks like:

public File file;

public DataStorage(String filePath) {
    setFile(filePath);
}

public Data read() throws IOException {
    Data db = new Data();
    Scanner scan = new Scanner(file);
    Person person;
    //check if file has data print selected data
    while(scan.hasNextLine()) {
        person = parsePerson(scan.nextLine());
        db.add(person);
    }
    if(scan != null) {
    // close() may throw IOException if fails;
    scan.close();
    }
    return db;
}
cchown
  • 21
  • 3

1 Answers1

-1

Instead of filePath, you need to pass the file object as an Argument and the path which you are sending is incorrect in the main method "C DRIVE IF WINDOWS" otherwise starts with \ i.e, File.separator for Mac

public class Stackex1 {
    public static void main(String args[]) throws IOException {

        String fileLocation = "C:"+ File.separator + "Users" + File.separator + "USERNAMEGOESHERE" + File.separator + "Desktop" + File.separator + "test.txt";
        System.out.println(fileLocation);
        File file = new File(fileLocation);

        DataStorage data = new DataStorage(file);
        data.read();
    }
}

class DataStorage {
    public File file;

    public DataStorage(File file) {
        setFile(file);
    }

    public void setFile(File file) {
        this.file = file;
    }
    .... //Remaining code goes here
Senthil
  • 1,619
  • 1
  • 10
  • 18