Joe
Joe

Reputation: 25

Android BufferedReader try-with-resources

Hopefully I can clearly ask my question this time, I embarrassed myself with my last question so I had to delete it.

This snippet is from a logger I am writing for my app. When I wrote this in Eclipse Luna, I was given no errors on the try() statement I made below, but when I plug the code into Android Studio, I am given an "Incompatible types" error. It states that the type found was "java.io.BufferedReader", and expected is "java.lang.AutoCloseable". What am I missing?

File filePointer = new File(logFile);
    boolean bool = false;
    bool = filePointer.exists();
    String ls = System.getProperty("line.separator");

    if(bool == true) {
        try (BufferedReader br = new BufferedReader(new FileReader(logFile))) {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while(line != null){
                sb.append(line);
                sb.append(ls);
                line = br.readLine();
            }
            copiedFile = sb.toString();
        }
        finally{
            br.close();
        }
    }

Upvotes: 1

Views: 793

Answers (1)

Larry Schiefer
Larry Schiefer

Reputation: 15775

Check your minimum API level. The java.lang.AutoCloseable interface wasn't added to Android until API 19. So the Java 7 'try-with-resources' feature isn't available unless you are building with Java 7 and your minSdkVersion is set to 19.

Upvotes: 1

Related Questions