首页 > 解决方案 > 从txt文件整数读取和打印java

问题描述

我编写了下面的代码,以便从文本文件中读取一些整数,然后在我将值 10 添加到每个整数之后,在每个整数中打印一个新的 txt。“-1” int 用作显示结束的指针。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;

public class SmallChallengeCh {
    public static void main(String[] args){
        Scanner in = null;
        PrintWriter pw = null;
        try{
            File f = new File("C:\\Users\\paioa\\primlnl.txt");
            in  = new Scanner(f);
            pw = new PrintWriter(new FileOutputStream("C:\\Users\\paioa\\primOut.txt"),true);

            int num = in.nextInt();
            while(num != -1 ){
                num = num + 10;
                System.out.print(num + " ");
                pw.print(num + " ");
                num = in.nextInt();
            }
        }catch(FileNotFoundException e1){
            System.out.println("The file does not exist");
        }finally {
            try{
                if(in != null) in.close(); else throw new Exception("NULL");
                if(pw != null) pw.close();else throw new Exception("NULL");
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
        }
    }
}

但是我收到以下错误

**Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at gr.aueb.elearn.ch6.SmallChallengeCh.main(SmallChallengeCh.java:18)
Process finished with exit code 1**

但我不明白为什么。inputmismatchexception 是由于我的文件可能不包含整数,但这不是真的,这里是 txt。

txt文件的输入,也用UTF-8编码保存


解决了

解答: 问题在于编码 UTF-8。我应该留下文件 ANSI。我不知道为什么我正在阅读/练习的示例提倡这一点..

标签: javaexceptiontextreadfile

解决方案


尝试这个

int num;
while(in.hasNextInt()){
    num = in.nextInt();
    num = num + 10;
    System.out.print(num + " ");
    pw.print(num + " ");
}

如果您只想读取“-1”之前的整数,您必须执行类似的操作

int num;
while(in.hasNextInt()){
    num = in.nextInt();
    if(num == -1)
        break;
    num = num + 10;
    System.out.print(num + " ");
    pw.print(num + " ");
}

推荐阅读