![](/img/trans.png)
[英]How to get data of an object that already existed in one class in another file and use it to another class in another file in Java?
[英]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");
}
}
}
您可以通過不同的方式來實現,
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.