Skipping Predefined Lines in FileReader - java

I've been programming a text-based RPG game, and I'm trying to implement a save game feature. Everything is coded and works correctly.
It works by having a file called "slist" that holds the name of the savegame and the "session ID Number". There is then a file for each savegame. The program scans this file to see if a savefile exists or not, then determines actions from there.
Note: I know this can be simplified a lot, but want to learn that on my own.
The problem I'm running into is that I want to be able to skip lines when reading from a file using FileReader. This is so users can share files with one another, and I can add comments for them at the top of the file (see below).
I've tried using Scanner.nextLine(), but it needs to be possible to insert a certain character anywhere in the file and have it skip the line following the character (see below).
private static String currentDir = new File("").getAbsolutePath();
private static File sessionList= new File(currentDir + "\\saves\\slist.dat"); //file that contains a list of all save files
private static void readSaveNames() throws FileNotFoundException {
Scanner saveNameReader = new Scanner(new FileReader(sessionList));
int idTemp;
String nameTemp;
while (saveNameReader.hasNext()) {
// if line in file contains #, skip the line
nameTemp = saveNameReader.next();
idTemp = saveNameReader.nextInt();
saveNames.add(nameTemp);
sessionIDs.add(idTemp);
}
saveNameReader.close();
}
And the file it refers to would look something like this:
# ANY LINES WITH A # BEFORE THEM WILL BE IGNORED.
# To manually add additional save files,
# enter a new blank line and enter the
# SaveName and the SessionID.
# Example: ExampleGame 1234567890
GenericGame 1234567890
TestGame 0987654321
#skipreadingme 8284929322
JohnsGame 2718423422
Is there are way to do this, or would I have to get rid of any "comments" in the file and use a for loop to skip the top 5 lines?

My Java's a bit rusty, but...
while (saveNameReader.hasNext()) {
nameTemp = saveNameReader.next();
// if line in file contains #, skip the line
if (nameTemp.startsWith("#"))
{
saveNameReader.nextLine();
continue;
}
idTemp = saveNameReader.nextInt();
saveNames.add(nameTemp);
sessionIDs.add(idTemp);
}

Related

Issues with FileReader and Java GUI/jForm

I am trying to make a smaller version of Pwned Passwords (https://haveibeenpwned.com/Passwords) for my Ap comp sci project. Everything is goo besides 2 things:
(Issue 1) (image of my code to show better)
I have this below my jForm source code which declares each button/etc and what they do. I get this error though: "Illegal static declaration in inner class PassCheck.check. I do not now how to resolve this issue.
The second issue is using FileReader and Buffered Reader. I want the program to read the text inputted from the jForm and compare it to a file which has a list of commonly used passwords. How can I do this? Here is my code so far of just practicing with FR and BR:
import java.io.*;
public class MainFileReader {
public static void main(String[] args) throws Exception{
String refpass, input;
input = "1234";
FileReader fr = new FileReader("C:\\Users\\tcoley\\Downloads\\207pass.txt");
BufferedReader br = new BufferedReader(fr);
while((input = br.readLine()) != null){
refpass = br.readLine();
And I stopped here. I apologize as Java is not my strong suit but any help is much appreciated!
For your issue #2 - input is the string variable that is to be used hold the password you want to find in the file yet you eliminate its contents when you apply it to reading a line: (input = br.readLine()). It will now hold the currently read file line (this is no good). You need to use the refPass variable instead, for example: (refPass = br.readLine()).
You only need to use br.readLine() once in your loop. What your code is effectively doing right now (if it runs) is reading two (2) file lines on each iteration of the while loop. It could potentially fall into an Exception since there is no protection for null in the second read. Again no good.
Once you've read a file line, ensure it actually contains something. A lot of times a file will have a blank line in it that can throw a monkey wrench into things if it's not handled. To check for this you can do something like what is shown below after a line is read into refPass:
while((refPass = br.readLine()) != null) {
// remove leading & trailing whitespaces (if any).
refPass = refPass.trim();
// Skip past blank lines in file (if any).
if (refPass.isEmpty()) {
continue;
}
// .... rest of code ...
}
Now to complete your loop block code, you just need to compare the password read in with the password contained within the input variable (ex: "1234"). To do this, you could have something like this:
if (refPass.equals(input) {
System.out.println("Password Found!")
break; // Break out of the 'while' loop and close file.
}
On a side: Don't use == to compare Strings for content equality, that may not always work as you expect. Use the String#equals() method instead. Give the supplied link a read.
At the end of and outside your while loop, be sure to close the reader, for example: br.close(); so as to release hold on the file and free up resources.
You don't need to use BufferedReader. Buffering is only for inefficient reading and writing (ie doing multiple reads and writes)
Use Path and Files instead
Path p = "C:\\Users\\tcoley\\Downloads\\207pass.txt";
String file = new String(Files.loadAllBytes(p));
What does the file look like? There are a lot of ways to format a file and for simplicities sake, this will just assume it's one word per line:
With the line
refpass = br.readLine();
You are taking in the line from the file
boolean isEqual = refpas.equals(input);
This allows you to assess the line individually.
Remember that '==' is not the way to use String comparisons in Java.
("cat" == "cat") != ("cat".equals("cat"))

How to start reading lines from text from beginning again?

So i have a scanner that reads through a text file of many lines using while(file.hasNext()), however after it reaches the end of the text file how do I make it so that I can start reading lines from the beginning again for a separate while loop?
If you want to read multiple files (example, "text1.txt, text2.txt, text3.txt..etc"), this is what you can do:
Implement your file reading within a method such as:
public void readFile(String filename){
//all the code for file reading goes here
}
String[] filesToRead = new String[]{"text1.txt", "text2.txt", "text3.txt"};
for(int x=0; x<filesToRead.length; x++) //iterate through the file names
readFile(filesToRead[x]); //repeatedly invoked to read various files
Certianly, you may also save the file names within another text file, and just read from there. This way you don't even have to recompile your program when you want to change the list of files to be read.
Example:
FilesToRead.txt
text1.txt
text2.txt
text3.txt

Do something upon file exist

so i created a java program that outputs to a file (classname.java) the basic template of a java program...
/*
Nathaly Morcillo
Nov 19 2013
Header comments
*/
public class test{
public static void main String([] args){
}
}
However what i don't understand is:
After collecting the required input, check to see if the requested file (classname.java) already exists. If it does not, the program proceeds as described above. If it does exist, the program simply adds the header comments (because you probably didn’t put them in before anyhow). Hint: since you have to read from then write to the same file, try using
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
method to read in and store the contents of the whole file before writing out the file plus the new header comments.
I don't understand what to do with the scan.useDelimiter("\\Z");
What I have is:
File outputFile = new File(outputFileName);
if (outputFile.exists()) {
} else {
pout.println(
System.out.println("Contents of file");
pout.close();
}
Since this looks like homework, I'm not going to give you the answer, but I'll try to explain what's going on and give you some hints.
Scanner scan = new Scanner(file);
This creates a new Scanner object, which will allow you to read from the given file.
scan.useDelimiter("\\Z");
A Scanner object splits its input into what are called tokens. It does this by using a delimeter. Basically, it looks for anything that matches its delimeter and cuts its input at every matching point. In your case, "\\Z" is a regular expression which matches only the end of input. That causes your Scanner to read in the entire file.
String content = scan.next();
This returns the next token in your Scanner's input. Since you set the delimeter to "\\Z", this is the entire file.
Now onto the actual program. Obviously, you can't read in from a file that doesn't exist, so you'd probably only want to use your Scanner if outputFile.exists() returns true.

Overwriting data in a file starting from a given line in java

I want to specifically overwrite data in a file starting from a given line.
Suppose that I find out that I have to write some data in the file from line x ( I have already found x) . How would I overwrite everything after there.
Also is there a function that would directly take my line and string and overwrite the file.
An alternate approach would be, read the file line by line by scanner class (as described below), store those lines into any variable, say, arraylist, then appennd your new string once you have read the lines and write the whole list into a new file.
Example:
File file = new File("file.txt");
Scanner scanner = new Scanner(file).useDelimiter("\n");
String line = scanner.next();
//Store in the list
//Append the new lines
//Write the whole list into a new file

java- read last 2 lines in a file and delete last line, then add 2 fixed string values at end of file

I want to read the last 2 lines in some files, and if the content of second last line matches a specific string, then delete the last line only.
Also, after the above operation, 2 lines of data have to be appended to the end of the modified file. I saw other questions on SO that deal with different parts of my problem, but is there an easy way of doing all of the above with minimal code, preferably in a single function? (I can combine the different functions available at SO but that would be messy...)
I would recommend you to do it "in memory". It's easy to read line by line into a List, check the last lines and update the lines and write it back to the file.
Example:
public static void main(String[] args) throws IOException {
String fileName = "test.txt";
List<String> lines = new ArrayList<String>();
// read the file into lines
BufferedReader r = new BufferedReader(new FileReader(fileName));
String in;
while ((in = r.readLine()) != null)
lines.add(in);
r.close();
// check your condition
String secondFromBottom = lines.get(lines.size() - 2);
if (secondFromBottom.matches("Hello World!")) {
lines.remove(lines.size() - 1);
lines.add("My fixed string");
}
// write it back
PrintWriter w = new PrintWriter(new FileWriter(fileName));
for (String line : lines)
w.println(line);
w.close();
}
Note: No exception handling is done in the example above... you need to handle cases where the file for example doesn't contain two lines and other problems!
If you have really big files and perfomance is an issue the way to go is to use a RandomAccessFile and read backwards looking for the line termination bytes to determine where the last two lines begin. Otherwise use dacwe's approach.
As Gandalf said you can:
take RandomAccessFile,
use method seek(long) to jump forward and read those lines. But you won't know exactly how big the jump should be.
to delete last lines you need the position of begin of last line so before reading each line store their file pointer position (method getFilePointer()). Deleting to that position you use setLength(long).
My example of reading and deleting last lines you have here:
Deleting the last line of a file with Java
Useful can be also:
Quickly read the last line of a text file?

Categories