2014-01-18 50 views
0

我有兩個類Test和Test2。 Test創建一個Test2實例,用於使用PrintStream和FileOutputStream寫入文件。write(String)在PrintStream中有私人訪問

我收到錯誤:

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

private方法只能從聲明它們的類中訪問。如果你需要被寫入文件換行符您可以使用print

output.print(str); 

println

閱讀:Controlling Access to Members of a Class

+0

有沒有寫原因是一個私有方法和println是不是?爲什麼javadoc沒有顯示[write](http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#write(int))是私有的? 雖然工作。 – Matthew

+0

您正在查看錯誤的'write'方法,它具有不同的簽名。問題中的問題需要一個字符串,它是[private](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/PrintStream.java# PrintStream.write%28char%5B%5D 29%)。我猜想'write(String)'只能用於內部使用 – Reimeus

+0

哦,我明白了。我看到的java文檔是不正確的還是我誤解了它們? – Matthew