javafileexceptionjava.util.scannerreader

I am trying to send File as a parameter to a method but dont know how?


public static void createFile() {

    File file = new File("C:\\Users\\egecoskun\\Desktop\\javafiles\\ananınamı.txt");
    try {
        if (file.createNewFile()) {
            System.out.println("Dosya olusturuldu!");

        } else {
            System.out.println("Dosya zaten var!");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

Here is my createFile method to create a file.

public static void readFile(File file) {
    try {
        Scanner reader = new Scanner(file);
        while(reader.hasNextLine()) {
            String line=reader.nextLine();
            System.out.println(line);
        }
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    }

}

and this method is reading the file i am creating.But it needs to take File as an argument but when i try to run this method in Main

public static void main(String[] args) {
    createFile();
    readFile(file);

}

The error i am getting is file cannot be resolved to a variable. Does anyone spot my mistake? Can you explain it please.


Solution

  • Return file object from createFile Function and pass it to readFile Function

    public static File createFile() {
        File dir = new File("C:\\Users\\egecoskun\\Desktop\\javafiles");
        if(dir.exists()) {
           dir.mkdirs();
        }
        File file = new File(dir,"ananınamı.txt");
        file.createNewFile();
        return file;
    }
    

    In your main function

    File file = createFile();
    readFile(file);