扫描仪输入问题

时间:2016-10-06 16:53:43

标签: java

我想将CSV文件与我编写的批处理文件合并,以便为我办公室的所有打印机制作安装程序。 xeroxTemplate.txt文件是一个批处理文件,如果导致格式问题,我将其重命名为txt。

运行时,会为第一个“for”循环抛出以下错误。我确认该文件确实有内容

java.util.NoSuchElementException: No line found

public class PrinterScriptCreator {

    public static void main(String[] args) {
        Scanner csvScanner = new Scanner("printers.csv");
        csvScanner.useDelimiter(",");
        Scanner txtScanner = new Scanner("xeroxTemplate.txt");

        try{
            while(csvScanner.hasNext()){
                //create file with name from first csv cell
                FileWriter fw = new FileWriter(csvScanner.next());
                PrintWriter pw = new PrintWriter(fw);
                //copy first 7 lines from xeroxTemplate.txt
                for(int i=0; i<7; i++){
                    pw.println(txtScanner.nextLine());
                }
                //copy the next three cells from CSV into new file
                for(int i=0; i<3; i++){
                    pw.println(csvScanner.next());
                }
                //copy remaining lines from TXT to the new file
                while(txtScanner.hasNextLine()){
                    pw.println(txtScanner.nextLine());
                }
            }  
        } catch (IOException ex) {
            System.out.printf("ERROR: %s\n", ex);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您实例化Scanner对象的方式,传递给构造函数的String被视为需要解析的内容。

Scanner csvScanner = new Scanner("printers.csv");
Scanner txtScanner = new Scanner("xeroxTemplate.txt");

这里尝试使用分隔符“,”解析字符串“printers.csv”。由于字符串中没有“,”,当您尝试读取以下代码中的第二个和后续值时,它会失败。

for(int i=0; i<3; i++){
    w.println(csvScanner.next());
}

如果您使用Scanner读取文件,一个选项是将文件对象传递给Scanner的构造函数。

试试这个,

File file = new File("printers.csv");
Scanner csvScanner = new Scanner(file);
相关问题