1

你好我对java和编程相当陌生。我想知道如何读取文本文件(test.txt)并实现它以执行一个过程,例如在链表中创建和删除节点以及为它们分配一个值。例如,如果 txt 文件读取:

插入 1

插入 3

删除 3

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

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

代码:

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());

  }

}

}
4

1 回答 1

2

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

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

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

于 2012-06-02T03:21:36.140 回答