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:
insert 1
insert 3
delete 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.
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());
}
}
}
If the command format in the file is always correct, you can wrap the input stream with Scanner and read word with
next(), followed bynextInt()to read the number. No need for complex input validation. This will even allow the number to be on different line from the command.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.