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

标签 java inputstream bufferedwriter

我正在尝试编写一段代码,它接受一个文件作为输入,并输出一个文件,如果没有整数,则每个整数后面都有空格。

示例:

输入文件包含: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/

相关文章:

java - 可靠地跳过 java.io.InputStream 及其子类型中的数据

Java Bufferedwriter 到可公开访问的位置

java - 在 Java 中追加到文本文件的特定部分

java - java中的线程概念

java - 读取java中存储为ascii字符的整数值

java - MQTT 应用程序使用单个客户端应用程序/库与两个代理连接

java - 如何通过runTime.exec()使用涉及 ">"的linux命令

java - DataInputStream.read 返回小于 len

java - 静态 JComboBox 未在 GUI 中显示

java - 使用 BufferedWriter 从用户获取输入并将其写入文件