使用文本文件携带Java中的命令 [英] Using a text file to carry commands in Java

查看:100
本文介绍了使用文本文件携带Java中的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我对Java和编程还是相当陌生的.我想知道如何读取文本文件(test.txt)并实施该文件以执行一个过程,例如在链接列表中创建和删除节点以及为其分配值.例如,如果txt文件显示为:

Hello I am fairly new to java and programming. I was wondering how to read a text file (test.txt) and implement it to carry out a procedure, such as creating and deleting nodes in a linked list as well as assigning them a value. For example if the txt file read:

插入1

插入3

删除3

我希望程序创建一个节点并为其分配值1,创建一个节点并为其分配值3,然后删除具有分配值3的那个节点.

I would want the program to make a node and assign it a value 1, make a node and assign it a value 3 and then delete that node that has the assigned value 3.

这是我到目前为止的一些粗略代码.谢谢.

This is some rough code I have so far. Thank you.

代码:

import java.io.*;

class FileRead 
{

  public static void main(String args[])
  {

    try
    {

      // Open the file that is the first 

      // command line parameter

      FileInputStream fstream = new FileInputStream("textfile.txt");

      // Get the object of DataInputStream

      DataInputStream in = new DataInputStream(fstream);

      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      String strLine;

      //Read File Line By Line

      while ((strLine = br.readLine()) != null)
      {

        // Print the content on the console

        System.out.println (strLine);

      }

      //Close the input stream

      in.close();

    }

    catch (Exception e){//Catch exception if any

    System.err.println("Error: " + e.getMessage());

  }

}

}

推荐答案

如果文件中的命令格式始终正确,则可以使用Scanner包装输入流,并使用next()读取单词,然后使用nextInt()来读号码.无需复杂的输入验证.这样甚至可以使数字与命令位于不同的行.

If the command format in the file is always correct, you can wrap the input stream with Scanner and read word with next(), followed by nextInt() to read the number. No need for complex input validation. This will even allow the number to be on different line from the command.

如果希望输入无效,为了简化起见,可以使用当前的逐行读取方案并检查命令.用.trim().split("\\s+")按行对行进行修剪和标记化.然后比较令牌数组中的第一项,并检查它是否是有效命令.调用相应的函数来处理该命令(如果有效),否则打印错误消息.

If you expect invalid input, to make it simple, you can use the current scheme of reading line by line and check the command. Trim and tokenize the line by space with .trim().split("\\s+"). Then compare the first item in the array of tokens and check whether it is a valid command or not. Call the corresponding function to handle the command if valid, print error message otherwise.

如果您有多个命令,则可以使用命令模式使代码更易于管理.

If you have multiple commands, you can use Command pattern to make your code more manageable.

这篇关于使用文本文件携带Java中的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆