簡體   English   中英

我如何在另一個類中使用一個文件對象

[英]how can i use one file object in another class

當我在另一個提供錯誤的類中使用文件對象時。 Java中有任何機制都可以在另一個類中使用對象。

class Abc {
    File file = new File("D:\\test.txt");
    BufferedReader br = new BufferedReader(new FileReader(alert_file));
}

class Def {
    File f_rename = new File("D:\\result.txt");
    if (file.renameTo(f_rename)) {
        System.out.println("file has been renamed");
    } else {
        System.out.println("file not renamed");
    }
}

您編寫的類僅是您首先需要實例化的模板。 在這里,您正在做的事情是將ABC類中定義的變量訪問到Def類中,直到在Def對象中擁有ABC類的對象后才允許訪問。 以下代碼演示了如何實現:

class MyClass{
     File file;
     public MyClass(){
        file=new File("somefile.txt");
     }
     //in some method you can write...
     public void someMethod(){
        SomeOtherClass soc=new SomeOtherClass(file);
        soc.someOtherMethod();
     }
} 

   class SomeOtherClass{
      File file; 
      public SomeOtherClass(File file){
        this.file=file;
      }
      public someOtherMethod(){
        //do whatever you want here with file object
      }
   }

您編寫的代碼段是錯誤的,

Abc類{

公共無效checkFile(){

File file = new File("D:\\test.txt");
BufferedReader br = new BufferedReader(new FileReader(alert_file));

}

}

Def類{

公共無效checkFile(){

File f_rename = new File("D:\\result.txt");
if (file.renameTo(f_rename)) {
    System.out.println("file has been renamed");
} else {
    System.out.println("file not renamed");
}

}

}

您可以通過不同的方式來實現,

  1. 靜態變量。
  2. 實例化obj&getter方法。
class Abc 
{
public static void main(String[] ars)
{
File file = new File("D:\\test.txt");
BufferedReader br = new BufferedReader(new FileReader(alert_file));
Def d=new Def();    
d.rename();
}
}

class Def {
public static void rename()
{
File f_rename = new File("D:\\result.txt");
if (Abc.file.renameTo(f_rename)) 
{
System.out.println("file has been renamed");
} 
else 
{
System.out.println("file not renamed");
}
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM