Java Check Vaild File - java

Please help, I need help on how to check for valid file names.
Here is part of my program...
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class BookstoreInventory
{
public static void main(String[] args)throws IOException
{
//Vaiable declartions
int edition, quanity;
double pricePerBook;
String isbn, author, title, publisherCode;
int totalQuant = 0;
double total = 0;
double totalValue = 0;
double sumOfPriceBook = 0;
//Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get the file name from the user
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
//Open the file and set delimiters
File file = new File(filename);
Scanner inputFile = new Scanner(file);
inputFile.useDelimiter("_|/|\\r?\\n");
}
}
So in my program I'm not sure how I would check to see if it's a valid file. For example, when the user enters "inventory" for the name of the file this will produce an error because the filename needs the .txt so the user should have entered "inventory.txt". So is there a way to adding the .txt to the name they entered? Or how do I check to see if a file is valid? Any help would be much appreciated.

You can try this:
if (!fileName.trim().toLowerCase().endsWith(".txt")) {
fileName+= ".txt";
}
Also, if you want to know if the file already exists or not:
File file = new File(filename);
// If file doesn't exist then close application...
if (!file.exists()) { System.exist(0); }
Hope this helps.

Try concatenating the user's input string by adding .txt. It should work.

Related

Array and File Creation

I am creating a code as part of my assignment by following the following guidelines:
Write a program that will continue to prompt the user for numbers until they enter "Done" to finish, then prompts the user for a file name so that these values can be saved to that file. For example, if the user enters "output.txt", then the program should write the numbers that have been read to "output.txt".
I have gotten near the end, but I cant seem to figure out why its not processing it the way i was expecting it to. For example, this is how it looks when i run it.
Please enter number. When complete, please input 'Done':
1
Please enter number. When complete, please input 'Done':
7
Please enter number. When complete, please input 'Done':
10
Please enter number. When complete, please input 'Done':
Done
File Contents 1710
Please enter file name: Test.txt
fileName: Test.txt
I would want the numbers (file contents) to read 1 7 10 and also to create a file which it is not.
Here is my code:
package labs.lab2;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Test4 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String fileContents = "";
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter number. When complete, please input 'Done': ");
String userInput = input.nextLine();
if ("Done".equalsIgnoreCase(userInput)) {
break;
}
fileContents += userInput;
}
System.out.println("File Contents " + fileContents);
Scanner input2 = new Scanner(System.in);
System.out.print("Please enter file name: ");
String fileName = input2.nextLine();
System.out.print("fileName: " + fileName);
//String fileNameFull = fileName + ".txt";
File file = new File(fileName);
//File file = new File(fileNameFull);
file.createNewFile();
// String fileName + ".txt";
// File file = new File(fileName + ".txt");
// file.createNewFile();
FileWriter myWriter = new FileWriter(fileName);
myWriter.write(fileContents);
myWriter.close();
you can find the absolute path of file that is created using
System.out.print("file path: "+file.getAbsolutePath());
you place this print statement after file.createNewFile();
if you find that, your file is created at this path
Other simple way it to refresh your project in IDE to find the file created in project

How to store multiple usernames in one textfile [duplicate]

This question already has answers here:
Java FileWriter with append mode
(4 answers)
Closed 2 years ago.
My program asks the user for their name and age. The username is their name and age plus a random character at the end of it. I want to store that username into a new text file but whenever I run the code it only writes one username at a time it doesn't include the one that I added before. Here is my code Please help me I am new.
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Userfile {
private static String name;
private static Scanner scanage;
private static Scanner scan;
public static void main(String[] args) throws IOException {
Random r = new Random();
int age;
String username;
char randomc = 2;
System.out.println("Please enter your name");
scan = new Scanner(System.in);
name = scan.nextLine();
System.out.println("Please enter your age");
scanage = new Scanner(System.in);
age = scanage.nextInt();
username = name.toLowerCase()+age;
String alphabet = "xy!&69£zHDErnABCabcFfGghIiJjKkLlMmNPp";
for (int i = 0; i < 1; i++) {
randomc = alphabet.charAt(r.nextInt(alphabet.length()));
String userId = username + randomc;
System.out.println("Your Username is " +userId);
}
FileWriter userid = new FileWriter("file path");
String userId = username + randomc;
userid.write("\n" + "Username: " + userId);
userid.close();
}
}
It's because you are overriding the file everytime.
Replace
FileWriter userid = new FileWriter("file path");
with
FileWriter userid = new FileWriter("file path", true);
If you want to write text to a file to which you've already written text before, you need to use the FileWriter(File file,boolean append) constructor:
FileWriter userid = new FileWriter("file path", true); //assuming "file path" is the actual path to the file
Besides that, your program only asks for input once, so you'll need to run it multiple times if you want to add multiple usernames. Or you could wrap what you've done in a loop to ask for input multiple times. And speaking of loops, the one loop you do have serves no real purpose as the statements it executes will run once, just like they would without a loop wrapping them.

Another java.io.FileNotFoundException (The system cannot find the file specified) thread

I've created a basic notepad text file (e.g., text-file.txt) and have tried placing this file in multiple file paths for my code to retrieve, but I can't seem to get this to work. Basically, I'm wanting to take the content of text-file.txt and create a second file where everything is in all caps.
Here is my code:
package abc123;
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class abc123
{
public static void main (String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
System.out.print("Please provide the name of your input file: ");
String inFileName = in.nextLine();
System.out.print("Please indicate what you'd like to name your output file: ");
String outFileName = in.nextLine();
FileReader reader = new FileReader(inFileName);
PrintWriter writer = new PrintWriter(outFileName);
Scanner fileReader = new Scanner(reader);
while(fileReader.hasNext())
{
String line = fileReader.nextLine();
line = line.toUpperCase();
writer.println(line);
}
fileReader.close();
writer.close();
System.out.println("The process is now complete. Please check your output file. Thank you.");
}
}
I'm a Java newbie, so a simple solution (and comments, as always) that I can grasp at this point would be super helpful. Thanks!
if the file isn't in the same folder as your java class, you have to give java full-path to find the file. be sure you also type the extension of the file, like ".txt".

change password of user account in java using text files?

I have a problem and hope to find a solution.
now i have created a simple program to change password of user account using text files in java.
now i should enter username of the account then change password of that account but there it shows me an error.
here is my code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Objects;
import java.util.Scanner;
public class Test6 {
public static void main(String[] args)throws IOException {
String newPassword=null;
boolean checked = true;
File f= new File("C:\\Users\\فاطمة\\Downloads\\accounts.txt");// path to your file
File tempFile = new File("C:\\Users\\فاطمة\\Downloads\\accounts2.txt"); // create a temp file in same path
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
Scanner sc = new Scanner(f);
System.out.println("Enter account username you want to edit password?");
Scanner sc2 = new Scanner(System.in);
String username = sc2.next();
while(sc.hasNextLine())
{
String currentLine= sc.nextLine();
String[] tokens = currentLine.split(" ");
if(Objects.equals(Integer.valueOf(tokens[0]), username) && checked)
{
sc2.nextLine();
System.out.println("New Password:");
newPassword= sc2.nextLine();
currentLine = tokens[0]+" "+newPassword;
checked = false;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
sc.close();
f.delete();
boolean successful = tempFile.renameTo(f);
}
}
the error shows to me:
Exception in thread "main" java.lang.NumberFormatException: For input string: "HAMADA"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at Test6.main(Test6.java:25)
the format of my text file is like that:
HAMADA 115599
JOHNY 4477100
Change Integer.valueOf(tokens[0]) on line 25 to just tokens[0].
In your code, you try to get the integer value of the username, when you should be getting its String representation. You do not need the Integer.valueOf(). (The error is thrown because you are trying to get the Integer representation of a non-integer type.)
On a side note, you should never have password-storing text files, especially when the passwords and the files are both unencrypted. Use a database instead.

Cannot instantiate the type Scanner

I am new to Java. I want to read input through scanner.
I am getting error as cannot 'instantiate the type scanner'.
import java.util.*;
import java.io.File;
public class Factors {
//string declaration
static String filename;
public static void main(String args[]){
//scanner initialization, needs to be done in every program that reads from user
Scanner input = new Scanner(System.in);
int caseIndex=0;
//prompts user for filename
System.out.println("Please enter the name of the file you would like to read from.");
filename = input.nextString();
//checks if filename exists
if(input.exists())
System.out.println(inp.getName() + "exists!");
else
System.out.println("File name does not exist!");
}
}
I am not understanding where i am lacking.
Please help. Thank you in advance.
Scanner does not have methods nextString() and exists() methods. I think your requirement is to check that file is present or not. Do it like this:
import java.util.*;
import java.io.File;
public class Factors
{
static String filename;
public static void main(String[] args)
{
//scanner initialization, needs to be done in every program that reads from user
Scanner input = new Scanner(System.in);
int caseIndex=0;
//prompts user for filename
System.out.println("Please enter the name of the file you would like to read from.");
filename = input.nextLine();
File file=new File(filename);
//checks if filename exists
if(file.exists())
System.out.println(file.getName() + "exists!");
else
System.out.println("File name does not exist!");
}
}

Categories

Resources