Java 从文本文件向控制台输入值,而不是手动输入值

Java 从文本文件向控制台输入值,而不是手动输入值,java,console,executor,Java,Console,Executor,我有一个程序Main.java: public class Main { public static void main() throws FileNotFoundException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter no: \t"); int sq=0;

我有一个程序Main.java:

public class Main {
  public static void main() throws FileNotFoundException 
      {       
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter no: \t");
      int sq=0;
      try {
        sq=Integer.parseInt(br.readLine());
    } catch (IOException e) {           
        e.printStackTrace();
    }         
    System.out.println(sq*sq);
  }
}
我不应该编辑上面的代码(Main.java),我应该从另一个java程序执行这个程序。因此,我算出了以下代码:

public class CAR {
public static void main(String[] args) {
    try {               
        Class class1 = Class.forName("executor.Main"); // executor is the directory in which the files Main.java and CAR.java are placed
        Object object = class1.newInstance();
        Method method = class1.getMethod("main", null);
        method.invoke(object, null);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}
通过运行CAR.java,以下是输出:

Enter no:   
2                  // this is the number I entered through the console
square is:   4
这很好。但是现在,我需要输入值到“sq”(Main.java中的变量),不是从控制台输入,而是从文本文件输入,使用程序CAR.java,而不编辑Main.java。如果不编辑Main.java,我想不出如何做到这一点

例如,如果chech.txt的内容为:10 100。 然后,通过运行CAR.java,我应该读取值10,并将其提供给等待的控制台,使其与“sq”的值相等,并将控制台上打印的输出与100进行比较。 并将CAR.java的输出打印为“测试通过”

请对此提出解决方案

可以将以下代码段添加到CAR.java以从文件中读取值:

File f = new File("check.txt");
BufferedReader bf = new BufferedReader(new FileReader(f));
String r = bf.readLine();
String[] r1 = r.split(" ");
System.out.println("Input= " + r1[0] + "    Output=  " + r1[1]);
System.setIn()发挥了神奇的作用…
它指定jvm,以更改从“System.in”获取输入的方式。例如:

System.setIn(new FileInputStream("chech.txt"));
这将从“check.txt”获取输入,而不是等待控制台的输入。示例程序:

public class systemSetInExample {

public static void main(String[] args) {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        try {
            System.out.println("Enter input:  ");
            String st=br.readLine();                 // takes input from console
            System.out.println("Entered:  "+st);    

            System.setIn(new FileInputStream("test.txt"));
            br=new BufferedReader(new InputStreamReader(System.in));
            st=br.readLine();                       // takes input from file- "test.txt" 
            System.out.println("Read from file:  "+st); 

    } catch (Exception e) {         
        e.printStackTrace();
    }
}

}

提示:查看System.setIn(),您可以尝试通过管道将CAR的输出传输到Main的输入,即
JavaCAR| Javamain