[英]java- Read data from a file for further processing
我是java的新手,我想向您寻求帮助。 我有一些数据存储在txt文件中,每行包含三个整数,以空格分隔。 我想从文件中读取数据,然后如果满足某些条件(在我的情况下-第三int大于50),则将该数据放入数组中以进行进一步处理。 我读了一些有关如何读取文件中的行数或文件本身的问题,但是我似乎无法将所有内容组合在一起以使其正常工作。 该代码的最新版本如下所示:
public class readfile {
private Scanner x;
public void openFile(){
try{
x = new Scanner(new File("file.txt"));
}
catch (Exception e){
System.out.println("could not find file");
}
}
public void readFile() throws IOException{
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("file.txt")));
int i = lnr.getLineNumber();
int[] table1 = new int[i];
int[] table2 = new int[i];
while(x.hasNextInt()){
int a = x.nextInt();
int b = x.nextInt();
int c = x.nextInt();
for (int j=0; j< table1.length; j++)
{
if(c > 50)
{
table1[j]=a;
table2[j]=b;
}
}
}System.out.printf(" %d %d", table1, table2);
}
public void closeFile(){
x.close();
}
}
main位于另一个文件中。
public static void main(String[] args) {
readfile r = new readfile();
r.openFile();
try {
r.readFile();
}
catch (Exception IOException) {} //had to use this block or it wouldn't compile
r.closeFile();
}
当我在printf方法上使用%d时,我什么都看不到,当我使用%s时,输出中有些乱码,例如
[I@1c3cb1e1 [I@54c23942
我应该怎么做才能使其工作(即,当c> 50时打印成对的ab)?
在此先感谢您的帮助,如果这确实是一个显而易见的问题,请您多多包涵,但是对于如何改善这一点,我真的没有足够的想法:)
您不能使用%d
打印整个阵列。 遍历数组并分别打印每个值。
由于在printf()
中打印数组引用,因此得到的输出乱码
对于单个值,请使用类似循环的方法。
for(int i:table1){
System.out.print(""+i)
}
要么
要成对打印,请替换以下代码...
if(c > 50)
{
table1[j]=a;
table2[j]=b;
System.out.printf("%d %d",a,b);
}
您不能使用printf将数组格式化为int格式。 如果要打印数组的全部内容,请使用辅助函数Arrays.toString(array)
。
例如
System.out.println(Arrays.toString(table1));
如果我答对的话,您有一个类似
12 33 54
93 223 96
74 743 4837
234 324 12
如果第三个整数大于50,则要存储前两个?
List<String> input = FileUtils.readLines(new File("file.txt"), Charset.forName( "UTF-8" ));
HashMap<Integer, Integer> filtered = new HashMap<Integer, Integer>();
for (String current : input) {
String[] split = current.split(" ");
if (Integer.parseInt(split[2]) > 50)
filtered.put(Integer.parseInt(split[0]), Integer.parseInt(split[1]))
}
System.out.println(filtered);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.