Do something upon file exist - java

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.

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"))

Java Scanner can't read from only File Name

I'm making a Java program to read some scores from a .csv file and calculate the average of those scores. To read from the file, I'm using the Scanner Class.
First, I create a scanner to read from my file:
Scanner scanner = new Scanner(new File("TempFile.csv"));
I expected this to work, but it returns a FileNotFoundException. So, I replaced TempFile.csv with the file's absolute file name.
Scanner scanner = new Scanner(new File(C:\\Users\....));
This gave me the result I wanted, and I was able to parse the file. I'm new to Java, but I know that it's bad practice to use the absolute file name.
How can I use only the short file name?
Scanner scanner = new Scanner(new File (new File("TempFile.csv").getAbsolutePath()));
Use above.
"TempFile.csv" is a relative path. It's relative to the working directory of your java program. This directory is the value of the System property "user.dir". The following line of code gives you that value...
String workingDirectory = System.getProperty("user.dir");
Hence if you are getting FileNotFoundException, it probably means file "TempFile.csv" is not located in the working directory of your java program.
By the way, since java 8, class java.nio.file.Files contains method readAllLines. So if file "TempFile.csv" is not too big, readAllLines may be a simpler alternative to class Scanner. Note though that you still need to provide the correct path to the file when calling that method.

Java Scanner hasNextLine returns false

I have several files (actually they are also java source files saved in Eclipse on Ubuntu) which I need to read and process line by line. I've noticed that I cannot read one of the files. The code I am using is as below
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine() ) {
builder.append(scanner.nextLine()).append("\n");
}
} catch (FileNotFoundException ex) {
System.out.println("Error");
}
I was checking beforehand if the file exists. And it does. I can even rename it. But I cannot read a single line. hasNextLine simply returns false. (I even try hasNext).
At the end I take a look at the content of the file and find that there is a different looking character (which was in the comment section of java file). It is the following character.
¸
When I delete this character, I can read the file normally. However this is not acceptable. What can I do to read the files even with that character in it?
This is most probably a character set issue, caused by the fact that the platform you are running your java code uses by default a different set; it is always a good practice to specify the expected/needed character set to be used when parsing, and with the Scanner class is just a matter of calling the constructor as:
Scanner scanner = new Scanner(file, "UTF-8");
where the second parameter is the character set literal, or even better:
Scanner scanner = new Scanner(file, StandardCharsets.UTF_8);

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

Skipping Predefined Lines in FileReader

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

Categories