import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class extractvalues {
@SuppressWarnings("null")
public static void main(String [] args)
{
try{
// command line parameter
FileInputStream fstream = new FileInputStream("c:/kdd.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
//to Read values
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
System.out.println(strLine);
String[] splitted=null;
//split the given line into array of words seperated by comma
splitted=strLine.split(",");
int i=0;
//continue loop till it find "." since everyline contain "." in the end
while(!".".equals(splitted))
{
//print each string one by one
System.out.println(splitted[i++]);
}
}
//Close the input stream
in.close();
}
catch (Exception e)
{//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
我在循环中运行2。第一个循环将从.txt文件中逐行读取,第二个循环将从行读取每个字符串。但是当我运行循环时它会读取第一行和字符串然后停止。我不知道我到达的地方错了。我错过了一些请帮忙!
答案 0 :(得分:0)
将内部while
循环更改为:
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
String[] splitted=null;
//split the given line into array of words seperated by comma
splitted=strLine.split(",");
for (int i=0; i < splitted.length; ++i ) {
if (splitted[i].equals("."))
break;
//print each string one by one
System.out.println(splitted[i]);
}
}
您正在引用整个数组splitted
,而不是访问数组中的元素,后者是您实际想要执行的操作。
答案 1 :(得分:0)
在我的本地计算机上运行你的代码并在此行获得异常 - ArrayIndexOutOfBounds
System.out.println(splitted[i++]);
答案 2 :(得分:0)
问题是拆分是String#Array
,你无法使用equals()
方法比较这样的数组
while(!".".equals(splitted)) ---> This is logically incorrect way !!
因此,请尝试forEach
循环并将数组中的每个字符串与.
for(String temp:splitted){
if(temp.equals(".")) <-- Using equals for comparing 2 String
break;
System.out.println(temp);
}
答案 3 :(得分:0)
将内部while循环更改为此,并确保不需要
if (splitted[i].equals("."))
因为字符串数组的最后一个索引不仅有(。),所以它也有额外的字符。
while ((strLine = br.readLine()) != null){
System.out.println(strLine);
String[] splitted=null;
//split the given line into array of words seperated by comma
splitted=strLine.split(",");
//continue loop till it find "." since everyline contain "." in the end
for(int i=0;i<splitted.length;i++)
{
System.out.println(splitted[i++]);
}
}