我正在尝试编写一段代码,它接受一个文件作为输入,并输出一个文件,如果没有整数,则每个整数后面都有空格。
示例:
输入文件包含:3 0001
输出文件应为:3 0 0 0 1
问题是,0001 被检测为 1,我的输出为
3 1
下面是我尝试的第一个代码
Scanner scanner = new Scanner(new File(inputPath));
ArrayList<Integer> integerArrayList = new ArrayList<Integer>();
while (scanner.hasNextInt()) integerArrayList.add(scanner.nextInt());
System.out.println(integerArrayList.toString());
scanner.close();
输出 - [3, 1]
尝试以角色的形式阅读
FileInputStream fin = new FileInputStream(new File(inputPath));
ArrayList<Integer> integerArrayList = new ArrayList<Integer>();
while (fin.available() > 0) integerArrayList.add(Integer.valueOf(fin.read()));
System.out.println(integerArrayList.toString());
fin.close();
现在输出是 - [51, 32, 48, 48, 48, 49]
最佳答案
尝试此代码并仔细阅读注释。
Scanner inp=new Scanner(new File(inputPath));
ArrayList<Integer> integerArrayList = new ArrayList<Integer>();
//looking for next string
while(inp.hasNext()){
String my_string=inp.next();//taking the string
for(int i=0;i<my_string.length();i++){//adding every character of string
try {//if a integer found add to list
integerArrayList.add(Integer.parseInt(String.valueOf(my_string.charAt(i))));
} catch (Exception ex) {
//exception occurs if an integer not found and do nothing
}
}
}
//printing values and here you can use your code to write in another file but use a space(" ") after every integer to get your desired output
for(int i=0;i<integerArrayList.size();i++){
System.out.print(integerArrayList.get(i)+" ");
}
关于java - 使用java在文件中的每个整数后面添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29579214/