**线程“main”中的异常java.util.InputMismatchException **

时间:2014-05-02 09:47:18

标签: java exception java.util.scanner

我正在尝试从txt文件中获取一些记录,并将这些记录放在以下Java程序中的数据库中

package Java_Demo;
import java.sql.*;
import java.util.*;
import java.io.*;

public class Jdbc_Demo {


    public static void main(String ...args)throws ClassNotFoundException,SQLException,FileNotFoundException {

        FileInputStream fin=new FileInputStream("C:/Users/steve-pc/Desktop/Employees.txt");
        Scanner s=new Scanner(fin);
        s.useDelimiter(",|\\n");

        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection con=DriverManager.getConnection("jdbc:oracle:thin:@172.22.22.131:1521:orcl","Demo","demo");
        while(s.hasNext())
        {

        PreparedStatement st=con.prepareStatement("Insert into Employee values(?,?,?)");

        String name=s.next();
        int  id=s.nextInt();
        int sal=s.nextInt();

        st.setString(1,name);
        st.setInt(2,id);
        st.setInt(3,sal);

        int result=st.executeUpdate();
        System.out.println("Records Changed: "+ result);

        }
        con.close();

    }

 }

我从中获取数据的txt文件格式如下

史蒂夫,12349,550000

标记,54321,250000

比尔,65478,350000

此外,EMPLOYEE表格式如下

名称ID工资

Varachar2号码

但代码正在生成以下错误

线程中的异常" main" java.util.InputMismatchException

at java.util.Scanner.throwFor(Scanner.java:909)

at java.util.Scanner.next(Scanner.java:1530)

at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Java_Demo.Jdbc_Demo.main(Jdbc_Demo.java:24)

3 个答案:

答案 0 :(得分:2)

进行如下更改:

public class ScannerTest {


    public static void main(String ...args)throws ClassNotFoundException,SQLException,FileNotFoundException {

        File f =new File("/home/rahul/Desktop/emp.txt");
        Scanner s=new Scanner(f);
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection con=DriverManager.getConnection("jdbc:oracle:thin:@172.22.22.131:1521:orcl","Demo","demo");
        while(s.hasNext())
        {

        PreparedStatement st=con.prepareStatement("Insert into Employee values(?,?,?)");

        String rcd = s.next();
        Scanner s1 = new Scanner(rcd);
        s1.useDelimiter(",|\\n");

        String name=s1.next();
        int  id=s1.nextInt();
        int sal=s1.nextInt();

        st.setString(1,name);
        st.setInt(2,id);
        st.setInt(3,sal);

        int result=st.executeUpdate();
        System.out.println("Records Changed: "+ result);

        }
        con.close();

    }

 }
}

答案 1 :(得分:2)

s.nextInt();给你错误。因为扫描仪接下来不能转换成整数。我建议,你使用s.next进行所有三个,然后使用Integer.parseInt(String)方法将它们转换为int

答案 2 :(得分:1)

我想知道你的文件中是否有空格?

如果是这样,你可以使用这样的东西来忽略它

            scanner.useDelimiter("\\s*,\\s*|\\n");

或者将每个标记读作字符串,然后整理并转换为int。