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

Time:12-11

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.

CodePudding user response:

createFile is void; that means it does not return anything. In this case, you want to return a File. Like,

public static File createFile() {
    File file = new File("C:\\Users\\egecoskun\\Desktop\\javafiles\\ananınamı.txt");
    try {
        if (file.createNewFile()) {
            System.out.println("Dosya olusturuldu!");
            return file;
        } else {
            System.out.println("Dosya zaten var!");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Then you need to assign the result of calling that method to a variable. And you should check that it is not null before you pass it to readFile. Like,

File f = createFile();
if (f != null) {
    readFile(f);
}

Note that the file won't actually contain anything to read. It just exists after you created it.

CodePudding user response:

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 = File(dir,"ananınamı.txt");
    file.createNewFile();
    return file;
}

In your main function

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