How to change the value of a file object? - java

In the following code, I'm trying to create a way to verify if what a user entered is a file that exists, and then prompts them repeatedly until they enter something that does exist.
System.out.print("Input file name: ");
String entry = console.nextLine().toLowerCase();
File f = new File(entry + ".txt");
while(!f.exists()){
System.out.print("File not found. Try again: ");
f.equals(console.next().toLowerCase() + ".txt");
}
Sorry if its a stupid question, I'm just new to java and don't know why this doesn't work. For example, if there's only one file named "testing.txt", and their first entry is "potato", I want it to prompt them until they enter the name of a file that does exist.

Try with below code
public static void main(String[] args) {
System.out.println("Enter File Name: ");
Scanner scanner = new Scanner(System.in);
File file = new File(scanner.nextLine()+".txt");
while(!file.exists())
{
System.out.println("File Not Found. Try Again...");
file = new File(scanner.nextLine()+".txt");
}
System.out.println("File Found. "+file.getName());
scanner.close();
}

Related

Why doesnt this code store multiple inputs - currently stores only one that gets overwritten upon new input

Hey guys any help would be appreciated.
I've created some code that allows me to take user input from terminal, and saves it into a txt file in the same directory. The issue is that only 1 name and surname is stored each time. when i open a new client and type a different name, it will just overwrite the original one. not sure what is the cause as i was under the impression that the out.newline would solve this issue.
public void userinput()
{
try
{
out = new BufferedWriter(new FileWriter("TESTING.txt"/*,true*/));
//
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//ask for first name
System.out.println("Please enter your first name: ");
Name = input.nextLine();
//ask for surname
System.out.println("Please enter your last name: ");
Surname = input.nextLine();
//write names into txt file
out.write(Name + " - " + Surname);
//print welcome message with names into console for user
System.out.println("Welcome " + Name + Surname);
out.newLine();
out.close();
}
catch(IOException e)
{
System.out.println("There was a problem:" + e);
}
}
}
thanks for the help!
This is happening simply because you didn't open your FileWriter in the append mode, so it doesn't overwrite the file every time. To do this, you have to call the constructor as new FileWriter("TESTING.txt", true). Just uncomment the true and it'll work. I'm guessing at some point you accidentally commented that out.

How to name a file using variable and returning the filename

My objective is to create a method in which a user inputs their first name and last name, and with this information a .txt file will be created and named using the first initial of the first name and the last name. For example if user enter Marcus Simmon, the text file created should be named "MSimmon.txt" and how would I be able to return this file name. Thank you in advance. This is my code so far...
public static String GetUserInfo() {
// complete with your code of the method GetUserInfo
Scanner input = new Scanner(System.in);
System.out.println("Please enter your first name: ");
char initial = input.next().charAt(0);
System.out.println("Please enter your last name: ");
String lastName = input.nextLine();
try{
FileWriter x = new FileWriter(initial + lastName + ".txt");
}
catch(IOException e){
System.out.println("ERROR");
}
}

Reading Data file and outputting to another file

Im trying to make a program that reads data from a text file which contains student names and scores they got on a test. I want to output it in this sort of way
Im starting off by trying to read the txt file so I can then re arrange them and then outputting it into another file but im not sure what im doing wrong. Instead it prints into the exe instead of the file I want it to print to.
import java.io.File;
import java.util.Scanner;
public class ReadConsole {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
input = new Scanner(file); //scans the file
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Click Here for Image
Instead of using System.out PrintStream, you can create a PrintStream that writes to a file:
PrintStream output = new PrintStream(new File("output.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
output.println(line);
}
Remember to close both input Scanner and output PrintStream:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
try (Scanner fileInput = new Scanner(file); // scans the file
PrintStream output = new PrintStream(new File("c:/output.txt"))) {
while (input.hasNextLine()) {
String line = input.nextLine();
output.println(line);
}
}
}

Java: FileNotFoundException ends completely

I've been stuck with this error for 3 hours, it is because in my CSE course we just learned to put in "throws FileNotFoundException" in methods however in my code:
public static void main(String[] args) throws FileNotFoundException {
Scanner user = new Scanner(System.in);
intro();
prompt(user);
}
public static void prompt(Scanner user) throws FileNotFoundException {
boolean game = true;
while(game != false) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String answer = user.next();
answer = answer.toUpperCase();
if(answer.equals("C")) {
create(user);
} else if(response == "V") {
view(user);
} else if(answer.equals("Q")) {
game = false;
}
}
}
public static void create(Scanner user) throws FileNotFoundException {
System.out.print("Input file name: ");
String fileName = user.nextLine();
Scanner file = new Scanner(new File(fileName));
File f = new File(fileName);
if(!f.exists()) {
System.out.print("File not found. Try again: ");
fileName = user.nextLine();
f = new File(fileName);
}
System.out.print("Output file name: ");
PrintStream ot = new PrintStream(new File(user.nextLine()));
filing(user, fileName, ot);
}
When ran through, and inputting in C: this is what happens.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story
The result will be written to an output file
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: Exception in thread "main" java.io.FileNotFoundException: (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.util.Scanner.<init>(Scanner.java:656)
at MadLibs.create(MadLibs.java:47)
at MadLibs.prompt(MadLibs.java:35)
at MadLibs.main(MadLibs.java:16)
Really confused for this in my CSE class, and I feel like they did not explain the process enough even after asking questions. Can anyone explain this? Thanks.
First of all you need to change the "fix" the following line:
String answer = user.next();
to read:
String answer = user.nextLine();
This means you will capture the newline, meaning it won't be buffered until the next Scanner call (preventing you from reading the filepath prompt).
Then some fixing here too. No need to create a new Scanner, you already have one which you can use:
System.out.print("Input file name: ");
String fileName = user.nextLine();
File f = new File(fileName);
if(!f.exists()) {
Since you are using user.next() to get the user input at first the scanner is reading the only next character but not the newline character.
So later on in your code when you do:
System.out.print("Input file name: ");
String fileName = user.nextLine();
The user.nextLine() call is just reading in the newline character left behind by the user.next() call.
One way you can fix this is by reading nextLine but ignoring the input like so:
user.nextLine();
System.out.print("Input file name: ");
String fileName = user.nextLine();
Now when prompted for the file name it will work correctly.

How to check if a file exists and loop to ask for new filename again if it doesn't exist?

public static String getFilename(Scanner getFile) throws FileNotFoundException {
System.out.print("\nEnter file name: ");
String filename = getFile.next();
File f = new File(filename);
if (f.exists()) {
System.out.println(filename + " exists.");
} else {
System.out.println(filename + " does not exist.");
getFilename(getFile);
}
return filename;
}
This is my current code. It asks me to type some text, then checks if my typed input is a file.
If the file exists, I want it to return the String that the filename is stored as, back to my main method.
If it doesn't exist, I want my method to restart(?). How do I loop it? My current method just re-calls the entire method but if I run this code, any input/filename that doesn't exist as a File will come up as an error.
File f = new File([filename]);
while(!f.exists()) {
f = new File([newFilename]);
}
// Do what you want to do with the file.
This also allows you to directly return the file instead of a filename, but you could return the filename like so:
String s = [filename];
File f = new File(s);
while(!f.exists()) {
s = [newFilename];
f = new File(s);
}
return s;
Keep in mind that this will infinitely loop if you don't ever provide a real file.
A loop is exactly what you need. Inside your method:
String fileName = "";
File f = new File(fileName);
while(!f.exists()) {
System.out.println("Enter file name: ");
fileName = getFile.next();
f = new File(fileName);
}
return f;
Basically, the code will prompt you for a file until you enter a file name that exists.
This should do the trick
String filename = null;
do{
System.out.print("Enter file name: ");
filename = getFile.nextLine();
} while (!new File(filename).exists());
after this loop you are sure filename refers to file which exists.

Categories