当我在另一个提供错误的类中使用文件对象时。 在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");
}
}
答案 0 :(得分:0)
您编写的类只是首先需要实例化的模板。这里你要做的是访问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
}
}
答案 1 :(得分:0)
您编写的代码片段错误,
班级Abc {
public void checkFile(){
File file = new File("D:\\test.txt");
BufferedReader br = new BufferedReader(new FileReader(alert_file));
}
}
class Def {
public void 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");
}
}
}
你可以通过不同的方式实现,
答案 2 :(得分:0)
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");
}
}
}