How can I compare an integer and a file name? - java

I am trying to make a login/password program which asks if you have an account and you can also make one.
By account I mean the program will give you a random 8 digit number.
I also have a FileWriter which creates a file based on the ID you were given. And I have a FileReader which will eventually read what you previously exported to your file so you can update it.
The problem I have is that when I ask the user if they have an account already, if they say yes it will ask the user for their UserID.
My plan was that when it read your UserID it would scan the folder I have my .java file saved in and look for a .txt file with the same name as your UserID. For example, if you make an account and the UserID it gives you is 12345678 it will create a file named 12345678 and then when you input you UserID it will scan to see if that file exists.
Currently The problem that occurs is the it prints
Error File Not Found(the catch String I wrote)
even though I have that file in the folder.
I think there is something wrong with how I am comparing to see if the UserID matches any file name.
The "Login" class.
import java.awt.*;
import hsa.Console;
import java.util.Random;
import java.io.*;
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.FileNotFoundException;
public class Login
{
static Console c;
static Login player1;
public static void main (String[] args)
{
player1 = new Login ();
player1.FileReaderTest (25756326);
//player1.Userlogin (); //I think it has something to do with this
} // main method
public void Userlogin (File input)
{
c = new Console ();
Random rand = new Random ();
c.println ("Hello do you have an account?");
String Q1 = c.readLine ();
Q1 = Q1.toUpperCase ();
if (Q1.equals ("YES"))
{
c.println ("Please input your User ID");
int login = c.readInt ();
if (String.valueOf(login).equals (input))//I think it has something to do with this
{
try
{
FileReader reader = new FileReader (input);
BufferedReader buf = new BufferedReader (reader);
String line1 = buf.readLine ();
String line2 = buf.readLine ();
buf.close ();
c.println (line1);
c.println (line2);
}
catch (FileNotFoundException e)
{
c.println ("Error File Not Found");
}
catch (Exception e)
{
c.println ("ERROR");
}
}
}
else if (Q1.equals ("NO"))
{
c.println ("Please enter your name ");
String name = c.readLine ();
int UserID = rand.nextInt (99999999);
c.println ("Your User ID is " + UserID);
player1.FileCreation (UserID);
player1.FileReaderTest (UserID);
}
while (!Q1.equals ("YES") && !Q1.equals ("NO")) //While Q1 != YES || NO
{
c.println ("Please Answer the question with Yes or No");
c.println ("Hello do you have an account?");
String Q2 = c.readLine ();
Q2 = Q2.toUpperCase ();
if (Q2.equals ("YES"))
{
c.println ("Ok lets start");
break;
}
else if (Q2.equals ("NO"))
{
c.println ("Please enter your name ");
String name = c.readLine ();
int UserID = rand.nextInt (89999999) + 10000000;
c.println ("Your User ID is " + UserID);
player1.FileCreation (UserID);
player1.FileReaderTest (UserID);
break;
}
} //While Q1 != YES || NO
} //Public void Main
public void FileReaderTest (int UserID)
{
File input = new File (String.valueOf (UserID));
player1.Userlogin (input);
try
{
FileReader reader = new FileReader (input);
BufferedReader buf = new BufferedReader (reader);
String line1 = buf.readLine ();
String line2 = buf.readLine ();
buf.close ();
c.println (line1);
c.println (line2);
}
catch (FileNotFoundException e)
{
c.println ("Error File Not Found");
}
catch (Exception e)
{
c.println ("ERROR");
}
}
public void FileCreation (int UserID)
{
try
{
Writer writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (String.valueOf (UserID)), "utf-8"));
}
catch (IOException ex)
{
}
}
} // Login class

So, you have a File input, and you want to compare the name of the file, so you instead want
String.valueOf(login).equals (input.getName());
If you are getting an error on
File input = new File (String.valueOf (UserID));
then note: "2.txt", for example, is very different than a file named just "2" (which is worth mentioning because Windows hides file extensions by default)
And if you aren't giving the full path to the file, then that file has to be in your "classpath", which if you don't understand, better to give the full path to the file.

FileNotFound is not thrown after a comparison but by your FileReader when it is created. FileReader tells you that there is not file named as such. Since you said that you did create the file, there can be a few explanations:
Maybe the file you created is in the wrong folder. The default folder for a java program is the project folder. Make sure that you have your file in the right folder. Else you can give the full path as an argument for the FileReader: "/my/full/path/filename.extension".
It can also be a problem of extension. If you are using a Windows OS, the extension may be hidden in the file explorer. Right clic on your file and check whether there is such an extension (ex: ".txt")
Eventually you can open the file with a FileWriter under Java, and try to create the file within your program. You will see more easily which file Java is trying to access and it will help you identify your issue.

Since you have mentioned that you need to create the text file associated with the UserId, I would suggest adding the ".txt" in the FileReaderTest class. Something similar to this :
File input = new File (String.valueOf (UserID)+".txt");
Or more conveniently
File input = new File (Integer.toString(UserID)+".txt");
I think this solves your query.

Related

having issues with Java reading input files using netbeans

Following is my code that I am working on for a school project. It does ok up until I try to read the animal.txt file. Can someone please tell me what I am doing wrong? I am attaching my compilation error as an image. Thanks in advance.
[input error image1
package finalproject;
//enabling java programs
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.FileInputStream;
import java.io.IOException;
public class Monitoring {
public static void choseAnimal() throws IOException{
FileInputStream file = null;
Scanner inputFile = null;
System.out.println("Here is your list of animals");
file = new FileInputStream("\\src\\finalproject\\animals.txt");
inputFile = new Scanner(file);
while(inputFile.hasNext())
{
String line = inputFile.nextLine();
System.out.println(line);
}
}
public static void choseHabit(){
System.out.println("Here is your list of habits");
}
public static void main(String[] args) throws IOException{
String mainOption = ""; //user import for choosing animal, habit or exit
String exitSwitch = "n"; // variable to allow exit of system
Scanner scnr = new Scanner(System.in); // setup to allow user imput
System.out.println("Welcome to the Zoo");
System.out.println("What would you like to monitor?");
System.out.println("An animal, habit or exit the system?");
mainOption = scnr.next();
System.out.println("you chose " + mainOption);
if (mainOption.equals("exit")){
exitSwitch = "y";
System.out.println(exitSwitch);
}
if (exitSwitch.equals( "n")){
System.out.println("Great, let's get started");
}
if (mainOption.equals("animal")){
choseAnimal();
}
if (mainOption.equals("habit")) {
choseHabit();
}
else {
System.out.println("Good bye");
}
}
}
\\src\\finalproject\\animals.txt suggests that the file is an embedded resource.
First, you should never reference src in you code, it won't exist once the program is built and package.
Secondly, you need to use Class#getResource or Class#getResourceAsStream in order to read.
Something more like...
//file = new FileInputStream("\\src\\finalproject\\animals.txt");
//inputFile = new Scanner(file);
try (Scanner inputFile = new Scanner(Monitoring.class.getResourceAsStream("/finalproject/animals.txt"), StandardCharsets.UTF_8.name()) {
//...
} catch (IOException exp) {
exp.printStackTrace();
}
for example
Now, this assumes that file animals.txt exists in the finalproject package
The error message clearly shows that it can't find the file. This means there's two possibilities:
File does not exist in the directory you want
Directory you want is not the directory you have.
I would start by creating a File object looking at "." (current directory) to and printing that to see what directory it looks by default. You may need to hard code the file path, depending on what netbeans is using for a default directory.

Problems with reading from a file in java, .txt file always erases

I'm taking a Grade 11 course in Java right now, and thus I am new to programming in Java. My assignment is to ask the user their name and a password, put their password on a .txt (the .txt file's name would be the name they input), and ask if they've played before (that's for the second half of the assignment). If they enter 'no' it will ask them to input a password for the future. If they exit and run the program again and input 'yes' then it will prompt the user to input the password they put in when they said 'no'.
Here's the code:
import java.io.*;
class passwordtest
{
public static void main (String args[])
throws java.io.IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
String name, password, input, filepassword;
System.out.println ("Please enter your name");
name = br.readLine ();
FileWriter fw = new FileWriter (name + ".txt");
System.out.println ("Have you played this game before?");
input = br.readLine ();
if (input.equalsIgnoreCase ("no"))
{
System.out.println ("Please enter a password that you can use for later.");
password = br.readLine ();
fw.write (password);
fw.close ();
}
if (input.equalsIgnoreCase ("yes"))
{
FileReader fr = new FileReader (name + ".txt");
BufferedReader bfr = new BufferedReader (fr);
filepassword = bfr.readLine ();
System.out.println ("Please enter your password");
password = br.readLine ();
if (!password.equals (filepassword))
{
System.out.println ("Wrong password.");
}
if (password.equals (filepassword))
{
System.out.println ("Right password. Enjoy the program!");
}
}
}
}
The problem here is that every time I run the program to say 'yes' the .txt file erases, thus making it impossible for me to be able to see if the user entered the correct password.
I've been struggling with this for the past couple of hours, please help.
FileWriter fw = new FileWriter (name + ".txt");
This is enough to create a new file. Place it carefully.

Having trouble searching a text file for strings

So I'm attempting to simulate a very basic search engine by reading a text file filled with data and then have a user search the file using some keywords, and then whichever "websites" contained in the text file that contain that keyword are returned back to the user. My code so far can read the text file (as far as I know), however no matter the entered keyword, the console almost always states that no results can be found (the text file doesn't contain the keyword(s). Thanks everyone.
Here's the appropriate code:
package myquery;
import java.util.Scanner;
import java.util.*;
import java.io.*;
public class MyQuery{
public static void main(String[] args){
Hashtable<String, ArrayList<String> > hash = new Hashtable<String, ArrayList<String> >();
Scanner input = new Scanner(System.in);
System.out.println("Here is where your .txt file(s) should be located for this program to work properly:");
System.out.println(new java.io.File("").getAbsolutePath());
System.out.println("\nEnter the filename that you want to Search values for. For example \"MyQuery.txt\"");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(input.nextLine()));
System.out.println("The file was found :) Here are the contents:");
while(reader.ready())
{
String currentline = reader.readLine();
String[] result = currentline.split("\\s");
for(int i = 0; i < result.length; i++)
{
if(!hash.containsKey(result[i]))
{
ArrayList<String> temp = new ArrayList<String>(1);
temp.add(currentline);
hash.put(result[i], temp);
}
else
{
ArrayList<String> temp = (ArrayList<String>)hash.get(result[i]);//
temp.add(currentline);
}
}
}
}
catch(Exception e)
{
System.out.println("Your file was not found unfortunately. Please try again.");
System.exit(1);
}
System.out.println(hash);
do
{
System.out.println("Enter a key to search for the value it is associated with.\n");
System.out.println(hash.get(input.nextLine()));
System.out.println("\nWant to try again? If so, press return and then follow the prompt. Type \"-1\" to quit");
}
while(!input.nextLine().equals("-1"));
try
{
reader.close();
}
catch(Exception e)
{
System.out.println(e);
System.exit(1);
}
}
}
And an example of one line in the text file:
www.Mets.com, "The New York Mets", baseball, team, NY
Here's an example of how the program should respond:
Enter a key to search for the value it is associated with.
Mets
www.Mets.com The New York Mets
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit
But here's what I'm getting instead:
Enter a key to search for the value it is associated with:
Mets
null
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit
ALTHOUGH. If I enter a word that matches any word besides the first/last ones, it works.
For example
Enter a key to search for the value it is associated with:
New
[www.Mets.com, "The New York Mets", baseball, team, NY, www.nytimes.com, "The New York Times", news]
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit

How to write code data into a text file

I just did a simple code which takes user name and phone number and save those into an arraylist by creating object. I want to save those information (name and phonenumber) into a text file so that all old information I can get again. How do I do it? Here is my code ...
import java.util.ArrayList;
import java.util.Scanner;
public class manager {
Scanner input = new Scanner(System.in);
ArrayList <objectclass> Test = new ArrayList <objectclass> ();
public void mainloop() {
for (int i = 0; i < 100; i++) {
String x;
System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER\n2 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");
x = input.nextLine();
if (x.equalsIgnoreCase("0")) {
System.out.println("Thank you!");
break;
}
if (x.equalsIgnoreCase("1")) {
String Name;
String Number;
System.out.println("Please Enter your Name below");
Name = input.nextLine();
System.out.println("Please Enter your Number below");
Number = input.nextLine();
objectclass objectclassObject = new objectclass(Name, Number);
Test.add(objectclassObject);
}
if (x.equalsIgnoreCase("2")) {
String y;
System.out.println("*** Enter your Name below for search ***");
y = input.nextLine();
for (objectclass p : Test) {
String z = p.getName();
if (z.equalsIgnoreCase(y)) {
System.out.println("Your Name is: " + p.getName() + "\nYour Number is: " + p.getNumber());
System.out.println("");
} else {
System.out.println("Contact not Found!\n");
}
}
}
}
}
}
I want to save all name and number that I store in arraylist into a text file ... how can I do it?
I tried this so far but don't know what to do next ...
import java.io.;
import java.lang.;
import java.util.*;
public class creatfile {
private Formatter x;
public void openFile(){
try{
x = new Formatter("testkyo");
}catch (Exception e){
System.out.println("you have an error");
}
}
public void addRecord(){
x.format();
}
public void closeFile(){
x.close();
}
You need to serialize an object in order to save it onto the file .
here's a tutorial on how to do it, its really simple.
When you serialize an object you can write it onto a file and then load it as it is from there .
EDIT :
example on how you could use this here , i guess the ObjectClass is the thing u want to save so :
class ObjectClass implements Serializable {
String name;
String number;
//constructor , setters , getters and w.e functions .
public static void main (String args[]){
try{
ObjectClass test = new ObjectClass("test",2);
File f = new File("path to file");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(test); // this will write the object as it is onto the file
out.close();
}catch(Exception ex){}
}
}
you wont be able to read the data cuz its serialised , but u can load them as objects like so :
ObjectInputStream in = new ObjectInputStream(new File("path to file"));
ObjectClass test =(ObjectClass) in.readObject(); // u have to cast from Object to Objectclass
what you propably want is an ObjectOutputstream writing your ArrayList to a file via an FileOutputStream when the porgram is exiting and reading the Arraylist with the coresponding InputStreams. See the links below:
http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html
http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html
A simple example:
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("./output.txt"));
writer.write("Hello World");
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
This will write "Hello World" in the text file named: "output.txt".
Check the java I/O api.
You can find a lot of tutorials on the web about this, like:
Reading, Writing, and Creating Files
Creating, Writing, Reading files using Java Files API of Java 7

Getting filenames from the command line and seeing if they exist in Java

So the following program should take in an input and output file as command line arguments. I'm entering in java FileCopy input.txt output.txt on the command line to run the program, which should put the file names in args. Testing this, I don't have any values in args. On top of this, method calls to fileExists() are not working, and I can't figure out why these calls aren't being executed. As a note, the getOutputFile method is incomplete, none of the code there currently gets executed due to the errors stated above.
class FileCopy
{
public static void main(String[] args) throws IOException
{
String infile = null;
String outfile = null;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
if (args.length >= 2) //both files given via command line
{
infile = args[0];
if (fileExists(infile) == false)
{
infile = getInputFile();
}
outfile = args[1];
}
else if (args.length == 1) //input file given via command line
{
infile = args[0];
outfile = getOutputFile(infile);
}
else //no files given on command line
{
infile = getInputFile();
outfile = getOutputFile(infile);
}
//create file objects to use
File in = new File(infile);
File out = new File(outfile);
/*
*rest of code
*/
}
//get the input file from the user if given file does not exist
public static String getInputFile() //throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
boolean haveFile = false;
while(haveFile == false)
{
System.out.println("Enter a valid filename for input:");
System.out.print(">> ");
try
{
fileName = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
haveFile = fileExists(fileName);
}
return fileName;
}
//get the output file and test things
public static String getOutputFile(String infile)
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
File input = new File(infile);
String filename = null;
boolean more = true;
while(more)
{
System.out.println("Enter a valid filename for output:");
System.out.print(">> ");
try
{
filename = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
File output = new File(filename);
if (output.exists())
{
more = false;
}
if (filename == infile)
{
int selection;
String inputString = null;
System.out.println("The output file given matches the input file. Please choose an option:");
System.out.println("1) Enter new filename");
System.out.println("2) Overwrite existing file");
System.out.println("3) Backup existing file");
System.out.print(">> ");
try
{
inputString = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
selection = Integer.valueOf(inputString);
switch (selection)
{
case 1: //new filename
case 2: //overwrite
case 3: //backup
default: System.exit(0);
}
}
}
return null;
}
//check the given file to see if it exists in the current working directory
public static boolean fileExists(String n)
{
return (new File(n)).exists();
}
}
just tested this in eclipse debugger and the commandline arguments are correctly placed in args, you may check if the file you test with are in your project folder or actual dir "." because if not it will otherwise prompt for new files anyway
if (fileExists(infile) == false)
{
infile = getInputFile();
}
Shouldn't the class be public?
public class FileCopy
Not sure if that will solve the problem or not.
You will need to enter a fully qualified path, depending on your project's structure. In my test environment, it defaults to the root level of the project in the IDE. Normally, the new File(n) call will default to the system-dependent default directory. I did compile and run this from a single directory with no package and was able to use the abstract file names successfully (i.e. input.txt and output.txt). Is there any harm in forcing users to supply full qualified file names or at least only ever check the args values. This would allow you to fail early on invalid arguments, rather than having to worry about prompting the users for additional filenames.

Categories