您好我是java和编程的新手。我想知道如何读取文本文件(test.txt)并实现它来执行一个过程,例如在链表中创建和删除节点以及为它们分配值。例如,如果txt文件读取:
插入1
插入3
删除3
我希望程序创建一个节点并为其赋值1,创建一个节点并为其赋值3,然后删除具有指定值3的节点。
这是我到目前为止的一些粗略代码。谢谢。
CODE:
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());
}
}
}
答案 0 :(得分:2)
如果文件中的命令格式始终正确,则可以使用扫描程序包装输入流并使用next()
读取单词,然后使用nextInt()
读取数字。无需复杂的输入验证。这甚至允许数字与命令在不同的行上。
如果您期望无效输入,为简单起见,您可以使用当前逐行读取方案并检查命令。使用.trim().split("\\s+")
按空格修剪和标记线。然后比较标记数组中的第一项,并检查它是否是有效命令。如果有效则调用相应的函数来处理命令,否则打印错误消息。
如果您有多个命令,则可以使用Command pattern使代码更易于管理。