【问题标题】:java use sanner for i/o and file redirectionjava 使用扫描仪进行 i/o 和文件重定向
【发布时间】:2014-09-25 04:54:34
【问题描述】:

我正在尝试读取输入(从键盘以及命令行文件重定向),处理输入信息。并将其输出到文件中。我的理解是使用以下代码,并使用命令行:java programName< input.txt >output.txtwe 应该能够将输出打印到文件中。但它不起作用。有人可以帮忙指出这样做的正确方法吗?非常感谢!

public static void main(String[] args) {

    Scanner sc = new Scanner (System.in);

    int [] array= new int[100];
    while (sc.hasNextLine()){
        String line = sc.nextLine();

        .....//do something

    }

【问题讨论】:

  • 你在哪里遇到问题?
  • 没有打印到控制台或输出文件

标签: java file printing io system.in


【解决方案1】:

试试下面的代码

import java.io.*;
import java.util.*;
/**
 *
 * @author Selva
 */
public class Readfile {
  public static void main(String[] args) throws FileNotFoundException, IOException{
   if (args.length==0)
   {
     System.out.println("Error: Bad command or filename.");
     System.exit(0);
   }else {
       InputStream in = new FileInputStream(new File(args[0]));
       OutputStream out = new FileOutputStream(new File(args[1]));
      byte[] buf = new byte[1024];
      int len;
      while ((len = in.read(buf)) > 0) {
         out.write(buf, 0, len);
      }
      in.close();
      out.close();
   }   
  }  
}

使用运行此代码 如果您的文本文件和 java 代码是同一个文件夹,请运行如下程序。

java Readfile input.txt output.txt

如果你的文本文件和 java 代码是不同的文件夹,运行下面的程序。

java Readfile c:\input.txt c:\output.txt

如果您使用扫描仪读取输入表单键盘。请尝试以下代码

import java.io.*;
import java.util.*;
    /**
     *
     * @author Selva
     */
    public class Readfile {
      public static void main(String[] args) throws FileNotFoundException, IOException{
       Scanner s=new Scanner(System.in);
       if (args.length==0)
       {
         System.out.println("Error: Bad command or filename.");
         System.exit(0);
       }else {
           System.out.println("Enter Input FileName");
           String a=s.nextLine();
           System.out.println("Enter Output FileName");
           String b=s.nextLine();
           InputStream in = new FileInputStream(new File(a));
           OutputStream out = new FileOutputStream(new File(b));
          byte[] buf = new byte[1024];
          int len;
          while ((len = in.read(buf)) > 0) {
             out.write(buf, 0, len);
          }
          in.close();
          out.close();
       }   
      }  
    }

【讨论】:

  • 感谢您的信息。这很有帮助。但是有没有办法避免使用 FileInputStream?我想对于输入流,它只能接受文件作为输入,但不能接受来自键盘的输入?
  • 查看我的答案以从键盘读取文件名。它按您的预期工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-09
  • 1970-01-01
  • 2017-10-25
相关资源
最近更新 更多