Search code examples
javafiletwitter4j

fill a file inside a inner class


I'm quiet new to java and I'm not even sure if the title makes any sense. Anyway how do I gain access to a file inside of onStatus? I'm just trying to write into a file in that function so in the code below "T_file.length()" the "T_file" cannot be resolved.

public static void main (){
    foo("file_name");
}

foo(String fileName)
{
        try{
        final File T_file = new File (fileName);
        final FileWriter fw = new FileWriter(fileName);
        final BufferedWriter bw = new BufferedWriter (fw);
        }catch (IOException e){}

        StatusListener listener = new StatusListener(){     
        public void onStatus(Status status){
            if (T_file.length() > 100){
                    System.out.println ("I have access here");
                  }
            }
        }

}

Solution

  • "T_file.length()" the "T_file" cannot be resolved

    This is because T_file is not in the scope of onStatus. You declare T_file in the foo method, but then create a new StatusListener in which you redefine the onStatus, but the compiler still see StatusListener as an other class.

    A workaround would be to declare the variable globally in your class, then access it specifying the name of your Class.this.T_file. Here an example :

    public class Foo {
    
        File T_file;
    
        public static void main (){
            new Foo("file_name");
        }
    
        Foo(String fileName)
        {
    
            T_file = new File (fileName);        
    
            StatusListener listener = new StatusListener(){     
                public void onStatus(Status status){
                    if (Foo.this.T_file.length() > 100){
                        System.out.println ("I have access here");
                      }
                }
            };
        }
    }
    

    This example would compile.

    Notice that I added a ; at the end of the StatusListener, else it would not compile.