繁体   English   中英

如何从文本文件java中读取数字和字母的组合

[英]How can I read a combination of numbers and letters from a text file java

我有这个包含各种信息的文本文件,到目前为止我已经能够阅读除地址详细信息之外的所有内容,因为它们用空格分隔并且包含数字和字母,所以我有点不知道该怎么做我已经尝试将其作为 int 读取,但我知道它行不通。

这是我的代码:

public void methodName() {
File vData = new File("src/volunteer_data.txt");    // Create file object
try {                                                        // try catch to handle exception
    Scanner readFile = new Scanner(vData);                   // Create scanner object
    while (readFile.hasNextLine()) {                         //
        int volunteerID = readFile.nextInt();                // Read volunteerID as an int
        String vName = readFile.nextLine();                  // Read volunteer name as string
        // DATATYPE address = readFile.nextSOMETHING();      // Read address as ....
        String contact = readFile.nextLine();                // Read contact number as a string
    }
    readFile.close();                                        // Close scanner
} catch(FileNotFoundException e) {                             // Throw exception and stop program if error found
    e.printStackTrace();
}

这是我正在阅读的文本文件。 它是制表符分隔的:

VolunteerID Name    Address Contact
050 John    24 Willow Street    905-747-0876
042 Emily   362 Sunset Avenue   905-323-1234
013 Alice   16 Wonderland Street    905-678-0987
071 Arthur  36 York Road    905-242-5643
060 Daniel  125 Ottawa Street   905-666-3290
055 Peppa   64 Great Britain Blvd   905-212-4365
024 Sean    909 Green Avenue    905-232-5445
077 Kim 678 Grape Garden    905-080-7641
098 Patrick 126 Oxford Street   905-099-9535
092 Laura   45 Mill Street  905-244-0086
008 Gary    84 California Street    905-767-3456

我的建议是忘记使用nextInt()等单独扫描每一列。从长远来看,这会导致痛苦和痛苦。 相反,扫描整行并处理该行:将其拆分为一个String[]列,然后分别处理这些列:

readFile.nextLine(); // skip heading line (if there is one)
while (readFile.hasNextLine()) {  
    String line = readFile.nextLine(); // read whole line
    String[] columns = line.split("\t"); // split line on tab char

    // get each column into variables
    int volunteerID = Integer.parseInt(columns[0]);
    String vName = columns[1];
    String address = columns[2]; // no big deal
    String contact = columns[3];

    // do something with variables
}

严格来说,您甚至不需要变量。 Yo 可以直接使用数组和索引,但是当您使用命名良好的变量时,它更容易阅读和调试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM