我有一个String,它位于一个单独的类中,我想在另一个String中引用它。
public static void filedemo(String[] args) {
FileDemo.readLibDir("C:/test/lib");
}
public static void readLibDir(String directoryname) {
File dir = null;
String[] paths;
try {
dir = new File(directoryname);
paths = dir.list(new FilenameFilter() {
public boolean accept(File directory, String name) {
// return only files that end .jar extension
return name.toLowerCase().endsWith(".jar");
}
});
// enhanced for loop used to iterate through the array
for (String path : paths) {
// check to see if jar filename exist
boolean found = FileNameStorage.exists(path);
if (found) {
// didn't find
FileNameStorage.delete(path);
} else {
System.out.print(path+" was not found.\n ");
}
}
} catch (Exception e) {
// if any error occurs
e.printStackTrace();
}
}
public class HtmlDataTable {
String lines = "<tr> <td>" + jarfilename + "</td> <td>"
+ paths + " </td> <td>" + jarfilename
答案 0 :(得分:0)
您的paths
变量是方法的本地变量。因此,无法从任何其他类(或甚至同一类中的任何其他方法)访问它。看看Variable Scope,或谷歌了解它。
如果您想从其他课程访问paths
,最简单的选择是将其设为实例变量并公开。
答案 1 :(得分:0)
如评论中所述,变量paths
应定义为类成员(当前在静态方法中定义为局部变量)。
只有这样才能使外部调用者可以使用它
一种方法如下:
public class FileDemo {
private final File dir;
// constructor
public FileDemo (String directoryname) {
dir = new File(directoryname);
}
public String[] getPaths() {
return dir.list(new FilenameFilter() {
public boolean accept(File directory, String name) {
// return only files that end .jar extension
return name.toLowerCase().endsWith(".jar");
}
});
}
:
public static void main(String[] args) {
FileDemo demo = new FileDemo("C:/test/lib");
String[] paths = demo.getPaths();
: // now it is available
}
}