![](/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.