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 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.
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.
Related
I am working on a program that involves me having to search a specific line in a .txt file and convert the string inside of it into something else.
For example, the string is actually made of numbers which I suppose I can convert into ints. The main thing is that for example, on line 2, there are 5 digits for zip code stored. I need to convert that into certain outputs, depending on the numbers. In other words, I need variables from digits 0-9 and depending on each digit, output a specific output.
Right now here is the code I have to prompt the user for information that is stored in the file, and can read and print all of the information that was just typed, but I'm unsure how to go about the rest.
import java.io.*;
import java.util.*;
import java.io.FileReader;
import java.io.IOException;
public class ObjectTest2 {
public static void main(String [] args) throws FileNotFoundException, IOException {
// The name of the file to open.
String fileName = "information.txt";
Scanner myScanner = new Scanner(System.in);
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// append a newline character.
//This shit here prompts the user for information and stores it in seperate lines to be
//called on by the later section.
System.out.print("What is your name? ");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your 5 digit zip code?");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your +4 digit zip? ");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your address? ");
bufferedWriter.write(myScanner.nextLine());
// Always close files.
bufferedWriter.close();
//reads the information file and prints what is typed
BufferedReader reader = new BufferedReader(new FileReader("information.txt")); {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
}
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
You are left with no choice but to iterate over each line of the file and search for the String. If you want to get a line of string from the file based on line number, consider creating a method. If the operation is required to be performed several times on the same file and if the contents of the file do not change, use a map to cache the file contents based on the line number.
I'm reading .txt file into my program and am adding lines of the .txt into a String arrayList. How do I add lines DELINEATED BY AN ENTER KEY (in .txt) into separate elements of the arrayList? Right now if I had the following written in text:
this is a test
test
test test
It would output:
this is a testtesttest test
What I want it to do is read things on a per line basis, and put it into different elements of the stringArrayList. So I want "this is a test" to be an element, and "test", and then finally "test test".
My code is really ugly, but right now all I want to do is get it to work for my purpose. My first purpose is getting to read a .txt by line. My second purpose is going to be parsing an element for a particular substring (a URL), connecting that URL to the internet, and then comparing a part of that page source of the webpage (parsing for a particular keyword) to the line ABOVE the substring I desire. But that's a question for another time :^)
import java.io.*;
import java.util.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "test.txt";
List<String> listA = new ArrayList<String>();
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
listA.add(line);
//*** THIS IS WHERE THE MAGIC HAPPENS ***\\ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open da file ofheee hah. '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
System.out.println();
System.out.println("array FOr loop thingy incoming:");
System.out.println();
for (int i = 0; i < listA.size(); i++) {
System.out.print((listA.get(i)).toString());
}
}
}
You just have to use println instead of print:
System.out.println((listA.get(i)).toString());
Alternatively, you can add the line break character \n
Your code seems to be working so far. If you just want to see what elements are in listA, just print it out:
System.out.println(listA);
Output:
[this is a test, , test, , test test, ]
Note that the extra lines in your input file are also being stored in listA. I'm not sure if that's the behavior you want.
I am trying to make a login screen that can read the usernames and passwords from a text file. I have already built the registration page which outputs the username and password to a file by executing the following:
try (BufferedWriter out = new BufferedWriter(fstream)) {
try {
out.write(username + " " + password);
out.newLine();
JOptionPane.showMessageDialog(null,"User Account '" + username + "' Created");
} catch (IOException ex) {
Logger.getLogger(ServerMenu.class.getName()).log(Level.SEVERE, null, ex);
}
}
the text file will looking something like this:
user1 password1
user2 password2
I have been reading through a lot of documentation to try and figure this one out however the more reading i do the more confused I get. The reason why I am doing it in this way is so that I can continue reading and writing to .dat files for the information that the system will eventually hold.
If anybody can help me in any way shape of form that would be amazing!
Thanks
C
Quick and easy solution. Each line is commented but if you need any help or if there's anything you don't get please let know.
import java.io.*;
class FileRead
{
public static boolean main(String lineToCompare)
{
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) {
//Compare the line with the line to compare (string)
if(strLine.compareTo(lineToCompare) == 0)
return true;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return false;
}
}
I am really not sure whether you want to execute the above code for a specific username and password, or all of them.
If you want to get specific line from the file, and you already have access to the offset of the line you want to read, you can use RandomAccessFile. This class lets you move the file pointer to a certain position, and then you can simply read the next line to get username and password.
However, if you want to read a specific line but have no information where that line could be in the input file, you will need to read each line (eg., using a BufferedReader) to find the one you need. You can also take this approach, if you want to read the files line by line.
I'm working on a program that needs to update a line that depends its value on the result of a line that goes read after. I thought that I could use two BufferedReaders in Java to position the reader on the line to update while the other one goes for the line that fixes the value (it can be an unknown number of lines ahead). The problem here is that I'm using two BufferedReaders on the same file and even if I think I'm doing right with the indexes the result in debug doesn't seem to be reliable.
Here's the code:
String outFinal
FileName=fileOut;
File fileDest=new File(outFinalFileName);
try {
fout = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(fileDest)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileReader inputFile=null;
try {
inputFile = new FileReader(inFileName);
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
BufferedReader fin = new BufferedReader(inputFile);
BufferedReader finChecker = new BufferedReader(inputFile); //Checks the file and matches record to change
String line="";
String lineC="";
int lineNumber=0;
String recordType="";
String statusCode="";
try {
while ((lineC = finChecker.readLine()) != null) {
lineNumber++;
if (lineNumber==1)
line=fin.readLine();
recordType=lineC.substring(0,3);//Gets current Record Type
if (recordType.equals("35")){
while(!line.equals(lineC)){
line=fin.readLine();
if (line==null)
break;
fout.write(line);
}
}else if (recordType.equals("32")){
statusCode=lineC.substring(4,7);
if(statusCode.equals("XX")){
updateRecordLine(line,fout);
}
}
}
returnVal=true;
} catch (IOException e) {
e.printStackTrace();
}
Thanks in advance.
Well, the BufferedReader only reads stuff, it doesn't have the ability to write data back out. So, what you would need is a BufferedReader to get stuff in, and a BufferedWriter that takes all the input from the BufferedReader, and outputs it to a temp file, with the corrected/appended data.
Then, when you're done (i.e. both BufferedReader and BufferedWriter streams are closed), you need to either discard the original file, or rename the temp file to the name of the original file.
You are basically copying the original file to a temp file, modifying the line in question in the temp file's output, and then copying/renaming the temp file over the original.
ok, i see some problem in your code exactly on these lines-->
recordType=lineC.substring(0,3);//Gets current Record Type
if (recordType.equals("35")){
if you see on the first line, you are getting the substring of recordType into recordType. Now recordType length is 3. If at all the recordType has only 2 characters, then substring throws arrayIndexOutOfBoundsException. So when no runtime exceptions, its length is 3 and on the next line you are calling the equals method that has a string with 2 characters.
Will this if block ever run ?
I want to read a text file in Java. After I finish, some text will be appended by another application, and then I want to read that. Lets say there are ten lines. When the other app appends one more line, I dont want to read the whole file again; just the new line. How can I do this?
Something like this could work:
BufferedReader reader = .. // create a reader on the input file without locking it
while(otherAppWritesToFile) {
String line = reader.readLine();
while(line != null) {
processLine(line);
line = reader.readLine();
}
Thread.sleep(100);
}
Exception handling has been left out for the sake of simplicity.
Once you get an EOF indication, wait a little bit and then try reading again.
Edit: Here is teh codez to support this solution. You can try it and then change the control flow mechanisms as needed.
public static void main(final String[] args) throws IOException {
final Scanner keyboard = new Scanner(System.in);
final BufferedReader input = new BufferedReader(new FileReader("input.txt"));
boolean cont = true;
while (cont) {
String line = input.readLine();
while (line != null) {
System.out.println(line);
line = input.readLine();
}
System.out.println("EOF reached, add more input and type 'y' to continue.");
final String in = keyboard.nextLine();
cont = in.equalsIgnoreCase("y");
}
}
EDIT: Thanks for adding some code Tim. Personally, I would just do a sleep instead of waiting for user input. That would more closely match the users' requirements.
You could try using a RandomAccessFile.
Open the file and then invoke the length() to get the length of the file. Then you can use the readLine() method to get your data. Then the next time you open the file you can use the seek() method to position yourself to the previous end of the file. Then read the lines and save the new length of the file.