Question


I have two classes, Test and Test2. Test creates an instance of Test2, which is used to write to a file with PrintStream and FileOutputStream.

I am getting the error:

    write(String) has private access in PrintStream
      output.write(str);
            ^

Why is it giving me this error if I'm correctly calling the private variable within the class it was declared in?

public class Test
{
    public static void main (String[] args)
    {
            Test2 testWrite = new Test2();
            testWrite.openTextFile();
            testWrite.writeToFile("Hello.");
            testWrite.closeFile();
    }
}

and

import java.io.*;

public class Test2{
    private PrintStream output;

    public void openTextFile(){
        try{
            output = new PrintStream(new FileOutputStream("output.txt"));
        }
        catch(SecurityException securityException){}
        catch(FileNotFoundException fileNotFoundException){}
    }
    public void writeToFile(String str){
        try{
            output.write(str);
        }
        catch(IOException ioException){}
    }
    public void closeFile(){
        try{
            output.close();
        }
        catch(IOException ioException){}
    }
}
Was it helpful?

Solution

private methods are only accessible within the class from which they are declared. You can use print

output.print(str);

or println if you need newline characters to be written to file.

Read: Controlling Access to Members of a Class

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top