-2

my Scanner doesn't read my existing File which is read by a BufferedReader but BufferedReaders don't support UTF-8 encoding which my file needs.

I've already used a BufferedReader(even with UTF-8 which didn't give me letters like "ä"(german letter) but gave me awkward question mark symbols instead). And I've of course already used a Scanner.

public ArrayList<String> getThemefile2() {
    Scanner s;
    try {
        s = new Scanner(themefile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return new ArrayList<>();
    }
    ArrayList<String> list = new ArrayList<>();
    while (s.hasNextLine()) {
        list.add(s.nextLine());
    }
    s.close();
    return list;
}

It just returns an empty ArrayList, but doesn't trigger the FileNotFoundException. themefile is an existing File.

Mrln
  • 1
  • 2

4 Answers4

0

You need to specify the encoding for the file, if it's anything other than your system default. In your case, this will be where you create the Scanner.

s = new Scanner(themefile, "UTF-8");
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
0

Without the file to look at, we're all just guessing at the problem.

Here's one guess: there is no next line, therefore the while loop immediately breaks off, and you get an empty arraylist. This would be the case if there is no newline at all in the text file.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
0

If you're using Java 8+ I would recommend to use Files#lines method:

try (Stream<String> stream = Files.lines(themeFile.toPath())) {
    stream.collect(Collectors.toList()); //need to be stored in a variable.
} catch (IOException e) {
    e.printStackTrace();
}

Documentations:

CodeMatrix
  • 2,124
  • 1
  • 18
  • 30
  • This one also throws following error: java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1 – Mrln Jan 07 '19 at 22:31
  • @Marlon Check [this](https://stackoverflow.com/questions/30609062/java-nio-charset-malformedinputexception-input-length-1) to solve the exception. – CodeMatrix Jan 07 '19 at 22:32
0

I had the same problem with api 28 level. This worked for me:

s = new Scanner(new FileReader(themefile));

and must import:

import java.io.FileReader;