【发布时间】:2016-10-29 05:54:09
【问题描述】:
我的问题是StringTokenizer似乎只读取了ip.txt的第一行
我要做的是从“ip.txt”加载一个 IP 地址列表并将其保存到一个数组中,以自动 ping 我网络上的设备以查看它们是否在线。无论我尝试什么,我都无法将“ip.txt”中的第一行添加到数组中。我的分隔符是“//”,ip地址的名称也存储在txt文件中。我包含了代码和文本文件的示例。
提前致谢!!
public class IP {
public static IP[] ips = new IP[100];
public static int total_ips=0;
String name;
String ip1;
String ip2;
String ip3;
String ip4;
String fullIP;
public static void read_ips() throws FileNotFoundException{
FileInputStream fstream1 = new FileInputStream("ip.txt");
String line;
String delimiter = "//";
StringTokenizer tokenizer;
BufferedReader input = null;
try {
int i = 0;
int totalIps = 0;
input = new BufferedReader(new InputStreamReader(fstream1));
line = input.readLine();
//outer while
while(line != null) {
tokenizer = new StringTokenizer(line, delimiter);
while(tokenizer.hasMoreElements()) {//process tokens in line
ips[i] = new IP();
ips[i].name = tokenizer.nextToken();
ips[i].ip1 = tokenizer.nextToken();
ips[i].ip2 = tokenizer.nextToken();
ips[i].ip3 = tokenizer.nextToken();
ips[i].ip4 = tokenizer.nextToken();
ips[i].fullIP = ips[i].ip1+"."+ips[i].ip2+"."+ips[i].ip3+"."+ips[i].ip4;
i++;
totalIps = i;
System.out.println(line);
}
line = input.readLine(); //next line
}//close outer while
total_ips = totalIps; // count of total cars
System.out.println("total_ips after i++ "+total_ips);
}catch (FileNotFoundException e) {
System.out.println("Unable to open file " + fstream1);
} catch (IOException e) {
System.out.println("Unable to read from file " + fstream1);
}finally {
// Close the file
try {
if (input != null)
input.close();
} catch (IOException e) {
System.out.println("Unable to close file " + fstream1);
}
}
}
}
这里是一个 ip.txt 的例子
Desktop1//192//168//1//127//
Desktop2//192//168//1//128//
Desktop3//192//168//1//129//
【问题讨论】:
-
只是提醒一下 Javadocs 对 StringTokenizer 的评价。 "... StringTokenizer 是一个遗留类,出于兼容性原因保留,但不鼓励在新代码中使用它。建议任何寻求此功能的人使用 String 的 split 方法或 java.util.regex 包. ...”
-
我尝试在我的机器上运行您的代码,它运行良好。它正在读取整个 ip.txt 文件。
标签: java arrays loops stringtokenizer inputstreamreader