将文件中内容读入作为java程序的输入

头文件:import java.io.FileReader;

方式一:

        1.BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

       2. reader = new BufferedReader(new FileReader("D:\\workspace\\nfv\\work"));
          String tempString = null;

 while ((tempString = reader.readLine()) != null) {

         。。。。

              }


方式二:

         FileInputStream fis=new FileInputStream("work");  

         System.setIn(fis);  //输入重定向(若不需要重定向,可不使用)

         Scanner sc=new Scanner(System.in);//创建一个Scanner对象实例

          while(sc.hasNextLine())  
        {  

。。。。

}

1.Scanner一个可以使用正则表达式来分析基本类型和字符串的简单文本扫描器,直接往硬盘写数据;Scanner取得输入数据的依据是空格符:如按下空格键,Tab键或者Enter键,Scanner就会返回下一个输入。Scanner不能输入空格,如果你希望取得含有空格的字符串BufferedReader可以做到。
BufferedReader是字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取。
2.System.in :InputStream类的对象实现标准输入,可以调用它的read方法来读取键盘数据。
System.out:PrintStream打印流类的的对象实现标准输出,可以调用它的print、println或write方法来输出各种类型的数据。
3.关于重定向
 
 

Java的标准输入/输出分别通过System.in和System.out来代表,在默认的情况下分别代表键盘和显示器,当程序通过System.in来获得输入时,实际上是通过键盘获得输入。当程序通过System.out执行输出时,程序总是输出到屏幕。

在System类中提供了三个重定向标准输入/输出的方法

static void setErr(PrintStream err) 重定向“标准”错误输出流

static void setIn(InputStream in)    重定向“标准”输入流

static void setOut(PrintStream out)重定向“标准”输出流

下面程序通过重定向标准输出流,将System.out的输出重定向到文件输出,而不是在屏幕上输出。

[java]  view plain  copy
  1. import java.io.FileOutputStream;  
  2. import java.io.PrintStream;  
  3. public class Test {  
  4.     public static void main(String[] args) throws Exception  
  5.     {  
  6.           
  7.         PrintStream ps=new PrintStream(new FileOutputStream("work"));  
  8.         System.setOut(ps);  
  9.         System.out.println("Hello World!");  
  10.   
  11.     }  
  12.       
  13.   
  14.   
  15.       
  16. }  

下面的代码将System.in重定向到文件输入,所以将不接受键盘输入

[java]  view plain  copy
  1. import java.io.FileInputStream;  
  2. import java.util.Scanner;  
  3.   
  4.   
  5. public class Test {  
  6.     public static void main(String[] args) throws Exception  
  7.     {  
  8.         FileInputStream fis=new FileInputStream("work");  
  9.         System.setIn(fis);  
  10.           
  11.         Scanner sc=new Scanner(System.in);  
  12.         while(sc.hasNextLine())  
  13.         {  
  14.             System.out.println(sc.nextLine());  
  15.         }  
  16.           
  17.   
  18.     }  
  19.       
  20.   
  21.   
  22.       
  23. }  
重定向内容参考自:http://blog.csdn.net/zhy_cheng/article/details/7891142



猜你喜欢

转载自blog.csdn.net/u013177799/article/details/76113478