使用java在文件中的每个整数后添加空格

时间:2015-04-11 14:51:04

标签: java inputstream bufferedwriter

我正在尝试编写一个代码,该代码将文件作为输入,并在每个整数后输出一个带有空格的文件,如果不存在的话。

示例:

Input file contains: 3 0001 Output file should be: 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]

3 个答案:

答案 0 :(得分:1)

试试此代码并仔细阅读评论。

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)+" ");
}

答案 1 :(得分:0)

除了读取和写入文件外,我还尝试实现您需要的逻辑。希望这会对你有所帮助!

试试这个:

public class SpaceLogic {
    public static void main(String[] args) {
      String chars = "3 0001";
      char[] charArray = chars.trim().replaceAll("\\s+", "").toCharArray();
      StringBuilder builder = new StringBuilder();
      for (char ch : charArray) {
        builder.append(ch).append(" ");
      }
      System.out.println(builder.toString());
    }
}

答案 2 :(得分:0)

简单的方法是将其读入String而不是Integer。如果你想确定它是一个整数,只检查字符串是否为整数:

String someString=readInputLine(); // Your input instructions
String[] someStringArray=someString.split("");

for(int i=0;i<someStringArray.length;i++) {
try {
   Integer intVal=new Integer(someStringArray[i]);
   yourwritefunction(intVal);
} catch(Exception exp) { System.out.println("Not an integer, skipping write"); }
}