【问题标题】:java copying all contents of one file to another using input to read/create the file namejava使用输入将一个文件的所有内容复制到另一个文件以读取/创建文件名
【发布时间】:2017-04-26 09:29:54
【问题描述】:

我在使用输入创建文件时遇到问题,我想在其中写入来自另一个文件的行。当我的代码到达我要创建的文件名时,它不允许我在输入后输入任何内容我要打开的文件的文件名。我认为这与扫描仪无法接收最后一个“\n”或其他什么有关,所以我在第一次调用它后尝试用 sc.nextLine() 来“刷新”它,但它没有不工作。我不太明白系统的逻辑不适用于第二个 nextLine(),它不应该与第一个相同吗?谁能解释一下?

        try {
            System.out.println("Enter the file name to open with extension: ");
            Scanner sc = new Scanner(System.in);
            File file = new File(sc.nextLine());
            sc = new Scanner(file); //opens inputted file name
//          System.err.println(file.getAbsolutePath());

            System.out.println("What is the file name you want to create? ");
//          sc.nextLine();
            File write = new File(sc.nextLine());

            PrintWriter writer = new PrintWriter(write);
//          System.out.println("Copying file contents over... ");
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                writer.println(line);
            }
            writer.close();
            sc.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

【问题讨论】:

    标签: java input file-io output java.util.scanner


    【解决方案1】:

    试试这个:

    try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter the file name to open with extension: ");
    
            File file = new File(br.readLine());
            Scanner sc = new Scanner(file); //opens inputted file name
    
            System.out.println("What is the file name you want to create? ");
            File write = new File(br.readLine());
    
            PrintWriter writer = new PrintWriter(write);
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                writer.println(line);
            }
            writer.close();
            sc.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    

    【讨论】:

      猜你喜欢
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 2013-04-26
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      相关资源
      最近更新 更多