Java输入输出重定向

        我们先来看一个程序,它的作用是累加输入的整数直到输入0。

       

import java.util.Scanner;

public class SentinelValue {
	/** Main method */
	public static void main(String[] args) {
		// Create a Scanner
		Scanner input = new Scanner(System.in);
		
		//Read an initial data
		System.out.print(
			"Enter an integer (the input ends if it is 0): ");
		int data = input.nextInt();
		
		// Keep reading data until the input is 0
		int sum = 0;
		while (data != 0) {
			sum += data;
			
			// Read the next data
			System.out.print(
			    "Enter an integer (the input ends if it is 0): ");
			data = input.nextInt();
		}
		
		System.out.println("The sum is " + sum);
	}
}

 

        每次都从键盘输入数据是非常繁琐的事情。可以将这些数据用空格隔开,并保存在一个名为input.txt的文本文件中,然后用下面的命令运行这个程序。

        首先是我的文件结构:

 

  然后是编译+运行(运行时不用手动输入,直接输入重定向,nextInt()挨个读取文本文件中的数字),结果就直接出来了:

 

      下面是文件内容。

        SentinelValue.java:

import java.util.Scanner;

public class SentinelValue {
	/** Main method */
	public static void main(String[] args) {
		// Create a Scanner
		Scanner input = new Scanner(System.in);
		
		//Read an initial data
		/*System.out.print(
			"Enter an integer (the input ends if it is 0): ");*/
		int data = input.nextInt();
		
		// Keep reading data until the input is 0
		int sum = 0;
		while (data != 0) {
			sum += data;
			
			// Read the next data
			/*System.out.print(
			    "Enter an integer (the input ends if it is 0): ");*/
			data = input.nextInt();
		}
		
		System.out.println("The sum is " + sum);
	}
}

 

        input.txt文件的内容如下:

 

 1 2 3 4 
  10 0    

 

    另外还有输出重定向,命令为

    java ClassName > output.txt

  它的作用就是将System.out.print或者println的内容打印到output.txt而不是控制台中,output.txt可以不存在。

   我们可以同时使用这两个命令:

    java SentinelValue <input.txt> output.txt

   刚开始的文件结构如下,此时准备执行重定向命令:  按下回车键执行命令后文件结构如下:

    此时多了一个output.txt, 而控制台没有任何显示,而output.txt的内容如下:

    正好是控制台输出的内容!

    其实不止是Java,C++也有类似的重定向语法,希望各位多实践!

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值