从txt文件整数java中读取和打印

时间:2018-12-15 19:58:04

标签: java exception text readfile

我编写了以下代码,以便从文本文件中读取一些整数,然后在将每个值加十后将每个整数打印为新的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并不正确。

Input of txt file, also saved with coding UTF-8


已解决

答案:问题在于编码UTF-8。我应该离开文件ANSI。我不知道为什么我正在阅读/练习的例子主张这个..

1 个答案:

答案 0 :(得分:0)

尝试

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