2016-02-25 77 views
1

我有文件句柄类:的Java:类之间发送变量

public class FileHandle { 
public static String a; 
public static String b; 
public static String c; 

public void openFile() throws FileNotFoundException { 
    File dir = new File("C:/Folder/DB"); 
    if (dir.isDirectory()) { 
     for (File file : dir.listFiles()) { 
      Scanner s = new Scanner(file); 
      //String f = file.getName(); 
      // System.out.println("File name:" + f); 
      while (s.hasNext()) { 
       a = s.next(); 
       b = s.next(); 
       c = s.next(); 
       System.out.printf("%s\n %s\n %s\n", a,b,c); 
      } 
     } 
    } 

和常量类:

public class Constants { 

FileHandle h = new FileHandle(); 
public static final String[] LIST_DATA = {FileHandle.a,FileHandle.b,FileHandle.c}; 
public static final int NEW_ELEMENT_ID = 0; 

} 

主要的问题:为什么在我的常量类我只得到最后扫描的文档信息。顺便提一下,要提到FileHandle类扫描仪工作正常,一切都很好。唯一真正的困难是将变量发送到Constants类,正如我所提到的,我只获取最后扫描的文档信息。

+0

你需要做'了''B'和'C'非静态。一般来说,你应该非常谨慎地使用非最终静态变量。 –

+0

但是,如果我不让他们静态我会能够让他们在常量类? – TheDude

+0

如果你让'h'静态,你可以。但目前尚不清楚你的期望是什么:你一再覆盖相同的变量。 –

回答

1

不确定是否了解您的问题。但是,假设要什么的是保持不同的呼叫跟踪,您可以:

  • abc连接字符串:

     a = (a == null) ? s.next() : a + " " + s.next(); 
         b = (b == null) ? s.next() : b + " " + s.next(); 
         c = (c == null) ? s.next() : c + " " + s.next(); 
    
  • 使abc名单:

    public static List<String> a = new ArrayList<String>; 
    public static List<String> b = new ArrayList<String>; 
    public static List<String> c = new ArrayList<String>; 
    ... 
         a.add(s.next()); 
         b.add(s.next()); 
         c.add(s.next()); 
    

由于静态值由同一类的所有实例共享,所以当您为其分配以覆盖所有以前的值时。

请注意:以上不使用同步,并且是线程安全的...

+0

所以我的问题是,静态覆盖所有以前的值,如你所说? – TheDude

+0

号码1方法工作:) – TheDude

+0

但也许你可以帮助我更多一点? :) – TheDude