关于键盘读取问题

A-Bruce 2015-09-23 04:06:59
使用自定方式进行键盘接收,当输入#的时候,读取结束,将在控制台所输内容保存到某个txt中。以下是目前代码
public static void main(String[] args) {
try {
//创建输入流接收键盘的输入
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//创建输出流
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("e:/c.txt")))) ;
//读取信息
String s = reader.readLine();

writer.write(s);
writer.flush();
writer.close();
reader.close();


} catch (IOException e) {
e.printStackTrace();
}
}
...全文
128 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
月凉西厢 2015-09-23
  • 打赏
  • 举报
回复
重定向输出就可以了

package test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;

public class TestForIn {
	public static void main(String[] args) {
		
		try {
			Scanner scanner=new Scanner(System.in);
			PrintStream systemOut=System.out;
			System.setOut(new PrintStream(new FileOutputStream("aa.txt")));
			
			String strTemp;
			while (scanner.hasNextLine()) {
				strTemp=scanner.nextLine();
				
				if (strTemp.endsWith("#")) {
					System.out.println(strTemp.substring(0, strTemp.length()-1));
					break;
				}
				
				System.out.println(strTemp);

			}
			
			scanner.close();
			System.setOut(systemOut);
			System.out.println("程序结束!");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}
这个逗b 2015-09-23
  • 打赏
  • 举报
回复
而且控制台本身是用enter来结束的 Scanner sc = new Scanner(System.in); String a =sc.next();
baidu_31006959 2015-09-23
  • 打赏
  • 举报
回复

public static void main(String[] args) {
		try {
		//创建输入流接收键盘的输入
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		//创建输出流
		BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("c:/c.txt")))) ;
		//读取信息
		String s = null;
		List<String> contents = new ArrayList<String>();
		while((s=reader.readLine())!=null){
			if(!s.equals("#")){
				contents.add(s+"\n");
			}else{
				break;
			}
		}
		for(String content : contents){
			writer.write(content);
		}
		writer.flush();
		writer.close();
		reader.close();


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

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧