制作一个命令行窗口程序

一杆长枪在 2018-01-12 08:04:05
制作一个命令行窗口程序,从键盘循环输入若干个字符串放入到泛型集合中,直到输入-1为止。将泛型集合中的字符串写入到文本文件1.txt中(每行一个字符串)。
...全文
583 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
2dot5 2018-01-17
  • 打赏
  • 举报
回复
我写了一个java的IM 客户端是键盘输入数据的 参考看看 java Socket 简单的即时聊天
什么都不能 2018-01-16
  • 打赏
  • 举报
回复
就是一个普通的application程序,从main函数进入,输入通过System.in流获取
  • 打赏
  • 举报
回复
List<String> strs = new ArrayList<String>(); Scanner input = new Scanner(System.in); String str=""; while(!(str=input.next()).equals("-1")){ strs.add(str); } try { //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 FileWriter writer = new FileWriter("d:\\1.txt", true); for(String content:strs){ writer.write(content); writer.write("\n"); } writer.close(); } catch (IOException e) { e.printStackTrace(); }
rickylin86 2018-01-13
  • 打赏
  • 举报
回复
看错了。还以为是一个窗口程序呢。哈哈
rickylin86 2018-01-13
  • 打赏
  • 举报
回复

import java.awt.Container;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.nio.file.StandardOpenOption.*;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class Test {

	public static void main(String[] args) {
		newFrame();
	}

	public static void newFrame() {
		JFrame frame = new JFrame();
		frame.setSize(300, 500);
		Container container = frame.getContentPane();
		container.add(textArea);
		textArea.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() != KeyEvent.VK_ENTER) {
					return;
				}
				String content = textArea.getText();

				Matcher matcher = Pattern.compile("(?m)^-1$").matcher(content);
				if (matcher.find()) {
					content = content.replaceAll("(?m)^-1$", "").replaceAll("(\n)+$", "\n");
					write(content);
				}
			}

			@Override
			public void keyPressed(KeyEvent e) {

			}
		});
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	private static void write(String content) {
		Path path = Paths.get(System.getProperty("user.dir")).resolve("content.txt");
		try (SeekableByteChannel channel = Files.newByteChannel(path, CREATE, WRITE, TRUNCATE_EXISTING)) {
			channel.write(ByteBuffer.wrap(content.getBytes()));
			System.out.println("写入成功");
			System.exit(1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static JTextArea textArea = new JTextArea();
}

62,614

社区成员

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

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