2015-02-09 66 views
0

假设有两个类:ExamMainExam(包含main方法)。 class Exam has a constructor如何将信息从文本文件传递给构造函数?

public Exam(String firstName, String lastName, int ID) 

MainExam这个类从tex tfile读取数据。例如,数据可以是:

John Douglas 57 

如何将数据从文本文件传递给构造函数?

+1

相同的方式,会从别的数据传递到构造函数。 – immibis 2015-02-09 07:50:21

+0

作为流或只是文件名/路径怎么样? – Stig 2015-02-09 07:51:00

+0

如何将数据放入对象? – jordan 2015-02-09 07:54:12

回答

0

下面是读取文件中的代码(以防万一你实际上并不拥有它)

Scanner scanner = new Scanner(new File("C:\\somefolder\\filename.txt"); 
String data = scanner.nextLine(); 

现在,假设你的文件中的行是按以下格式:

<FirstName> <LastName> <id> 

无需在每个元素任何空白,您可以使用正则表达式" "String#splitdata

String[] arguments = data.split(" "); 

,然后将它们传递到构造函数(字符串,字符串,INT)

String fn = data[0]; 
String ln = data[1]; 
int id = Integer.parse(data[2]); 
new Exam(fn, ln, id); 
0

您可以参考下面的代码片段,以文本文件的内容存储在一个字符串对象:

BufferedReader br = null; 
    try { 
      String sCurrentLine; 
      br = new BufferedReader(new FileReader("C:\\testing.txt")); 
      while ((sCurrentLine = br.readLine()) != null) { 
      // System.out.println(sCurrentLine); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (br != null)br.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 

该文件的内容是sCurrentLine对象现在。使用StringTokenizer,您可以使用空格作为分隔符来区分名字,姓氏和ID。希望这可以帮助!!

0

您可以使用StringTokenizer将数据分解为由MainExam读取的部分。

String str; //data read by MainExam, like: John Douglas 57 
String[] values = new String[3]; // size acording to your example 
StringTokenizer st = new StringTokenizer(str); 
int i=0; 
while (st.hasMoreTokens()) { 
    values[i++] = st.nextToekn(); 
} 

现在您已将数据在数组values中分隔。

+0

感谢您的尝试,但StringTokenizer不允许用于我的项目 – jordan 2015-02-09 08:08:17

+0

这意味着您甚至不允许手动标记字符串? – minarmahmud 2015-02-09 08:09:55

相关问题