0

My scanner wont close when i have multiple assignments to it.. With this code i get resource leak on the [second in = new Scanner(textfile);]

However if i a new scanner it works. Is there any way? maybe possible to make the scanner go to first line again, so that i dont have to assign the scanner textfile to it again?

public static String[][] lesFil(Scanner input) {

        Scanner in;
        String fileName = "d";

        try {

            in = new Scanner(textfile);

            while (in.hasNextLine()) {

                in.nextLine();
            }


            in = new Scanner(textfile);

            while (in.hasNextLine()) {

                in.nextLine();
            }
            in.close();

        } 
        catch (FileNotFoundException e) {


        }

        return null;
    }

EDIT: First while loop counts the number of lines in the textfile (To set an array size), then the second while stores the data of the file in a string array.

user2725580
  • 1,293
  • 2
  • 17
  • 21

2 Answers2

2

The answer seems obvious, you should close the scanner before re-assigning your 'in' to another scanner.

Though you should probably just do the 2 tasks you have in the same iteration, IO is one of the few things that is actually quite expensive in terms of resources.

Additionally, if you don't need something from the Scanner directly and just want to read lines, why not use a FileReader and BufferedReader instead? If you can use Java 7, you might even want to use Files.readAllLines (see https://stackoverflow.com/a/12838276/144578)

Community
  • 1
  • 1
Sebastiaan van den Broek
  • 5,818
  • 7
  • 40
  • 73
0

Rather than using two while loops, you may prefer to read each line into an ArrayList the first time around.

ArrayList<String> lineList = new ArrayList<String>();
while (in.hasNextLine())
{
    lineList.add(in.nextLine());
}
in.close();

String[] stringArray = new String[lineList.size()];
lineList.toArray(stringArray);

If you instead want to jump around while reading, I would suggest using a BufferedReader() instead of a scanner and use a FileInputStream.

DoubleDouble
  • 1,493
  • 10
  • 25