简体   繁体   English

Java使用sanner进行I / O和文件重定向

[英]java use sanner for i/o and file redirection

I am trying to read input (from keyboard and also with command line file redirection), process the input info. 我正在尝试读取输入(从键盘以及使用命令行文件重定向),处理输入信息。 and output it to a file. 并将其输出到文件中。 My understanding is that using the following code, and use command line: java programName< input.txt >output.txt we should be able to print the output to a file. 我的理解是,使用以下代码并使用命令行: java programName< input.txt >output.txt我们应该能够将输出打印到文件中。 But it doesn't work. 但这是行不通的。 Can someone please help to point out the correct way of doing this? 有人可以帮忙指出正确的做法吗? Many thanks! 非常感谢!

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

    }

Try the below code 试试下面的代码

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();
   }   
  }  
}

Run this code using If your text file and java code is same folder run the program like below. 使用以下代码运行此代码:如果您的文本文件和Java代码是同一文件夹,请运行以下程序。

java Readfile input.txt output.txt java Readfile input.txt output.txt

If your text file and java code is different folder run the program like below. 如果您的文本文件和Java代码是不同的文件夹,请运行以下程序。

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

If you read input form keyboard using scanner.Try the below code 如果您使用扫描仪阅读输入法键盘,请尝试以下代码

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();
       }   
      }  
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM