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

标签 java private-members printstream

<小时/>

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

我收到错误:

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

如果我在声明它的类中正确调用私有(private)变量,为什么会出现此错误?

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

最佳答案

私有(private)方法只能在声明它们的类中访问。您可以使用打印

output.print(str);

println 如果您需要将换行符写入文件。

阅读:Controlling Access to Members of a Class

关于java - write(String) 在 PrintStream 中具有私有(private)访问权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21211452/

相关文章:

java - 如何以编程方式终止liferay中的 session /注销其他用户

java - 为什么这个基本的客户端-服务器程序不传递数据?

Java Socket OutputStream 未刷新

Java 新手需要帮助查找有关 'new classname().withXxx(param)' 和 ClassName.class.method 语法的进一步阅读

java - 组件的定位(如何将几个按钮放置在屏幕中央相同大小)

python - Pylint W0212 protected 访问

c++ - 在 C++ 中将虚函数设为私有(private)

class - 方法在Perl 6中返回正则表达式?

java - PrintStream 无缘无故出错?

java - Java有这样的字母顺序吗?