write(String)在PrintStream中具有私有访问权限

时间:2014-01-18 23:56:20

标签: java private-members printstream


我有两个类,Test和Test2。 Test创建Test2的实例,该实例用于使用PrintStream和FileOutputStream写入文件。

我收到错误:

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

如果我在声明的类中正确调用私有变量,为什么它会给我这个错误?

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

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){}
    }
}

1 个答案:

答案 0 :(得分:1)

private方法只能在声明它们的类中访问。您可以使用print

output.print(str);
如果您需要将换行符写入文件,请

println

阅读:Controlling Access to Members of a Class