0

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){}
    }
}
Mdev
  • 2,440
  • 2
  • 17
  • 25

1 Answers1

1

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

Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Is there a reason write is a private method and println is not? Why do the javadocs not show that [write](http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#write(int)) is private? That worked though. – Mdev Jan 19 '14 at 00:06
  • You're looking at the wrong `write` method there which has a different signature. The one in the question takes a String which is [private](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/PrintStream.java#PrintStream.write%28char%5B%5D%29). I would guess that `write(String)` is only meant for internal use – Reimeus Jan 19 '14 at 00:09
  • Oh, I see. Are the java docs I'm looking at incorrect or am I misinterpreting them? – Mdev Jan 19 '14 at 00:21
  • 1
    `private` methods are not published in the javadoc so `write(String)` wont appear at all... – Reimeus Jan 19 '14 at 00:24