Uppercase Conversion - java

import java.util.Scanner;
import java.io.*;
public class UppercaseFileConverter {
public static void main(String[] args) throws FileNotFoundException{
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the file to be read: Here is the file converted into Uppercase.");
String fileName = input.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
//validates that the file exists
if (!file.exists()) {
System.out.println("The file " + fileName + " does not exist or could not be opened.");
System.exit(0);
}
//if file exists then reads each line and prints the upper case
else {
while (inputFile.hasNext()) {
String line = inputFile.nextLine();
System.out.println(line.toUpperCase());
}
}
inputFile.close();
System.out.println("Files read, converted and then closed.");
}
}
When I run my code, my validation that checks whether the file entered exists or not does not run but instead terminates the program. Can I use a try/catch?

You can do three things
1.Remove System.exit()
2.Add null Check before using file object
if (file!=null&&!file.exists()) {}
3.Add try catch block to handle possible exception in your case FileNotFoundException.

Related

Ckecking if a folder from the input exists and asking to type again in java

I am trying to read a folder path from the user and check if exists or not.If it does not exist I want to ask from the user to type the path again using a while loop .The problem is that even if the user types a correct path my program asks to type again .I am preety sure that the solution is easy and that the problem is in the loop but I can not see it. Please help me because I am a new programmer in Java.
public class JavaProject {
public static void main(String[] args) throws IOException {
//Taking the name of the folder from the user
System.out.println("Give me the path of the folder");
Scanner fold =new Scanner(System.in);
String folderName= fold.nextLine();
File f= new File(folderName);
//Check if the file exists
boolean exists = f.exists();
boolean folderIsValid=true;
while(folderIsValid){
if(!exists){
System.out.println("The folder you are searching does not exist :" +exists);
System.out.println("Try again!");
folderName= fold.nextLine();
}else{
System.out.println("The folder you are searching exists :" +exists);
folderIsValid=false;
}
}
}
}
use do while loop, do at least once, then while check exit do while loop or contine do next loop.
import java.util.Scanner;
import java.io.File;
public class JavaProject {
public static void main(String[] args){
boolean isExistingDir = false;
do {
System.out.println("Give me the path of the folder");
Scanner input = new Scanner(System.in);
String dirName = input.nextLine();
System.out.println(">>" + dirName);
File f =new File(dirName);
if (f.exists()==true) {
isExistingDir=true;
System.out.println("EXISTING >>" + dirName);
} else {
System.out.println("NOT EXISTING >>" + dirName);
System.out.println("PLEASE INPUT A EXISTING AGAIN");
}
} while (!isExistingDir);
} //main
}

How can I let user input the name of text file again if the name of file already exists?

public static void textFileOpen(String fileName) throws IOException
{
while(true)
{
try
{
FileReader fileReader = new FileReader(fileName);
LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
BufferedReader bufferedReader = new BufferedReader(fileReader);
fileReader.close();
bufferedReader.close();
lineNumberReader.close();
}
catch(Exception ex)
{
System.out.println("File " + fileName + " does not exists! Please try again.");
}
}
}
I'm trying to let the user input file name again if exists. But it runs forever if user enter an exist file name. How can I fix it? Can anyone help, please? THank you
The cause is your use of try(input). As the scanner has already been closed after the first catch , it is not able to take any new input.
Remove the (input) and use a separate input.close should work.
You shouldn't close a Scanner that wraps System.in since System.in represents the standard input which is generally the computer keyboard. So when you close it, your program cannot receive input from the keyboard.
You should also not use exception handling to test a condition. You should use a conditional statement, like an if statement.
In order to test whether a file exists, you can call method isFile. The method returns...
true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise
When you create a FileWriter, it also creates the file if it doesn't already exist.
Here is code demonstrating the above.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Cipher {
public static void main(String[] args) throws IOException {
System.out.println("Enter fileName: ");
Scanner input = new Scanner(System.in);
String fileName = null;
File file = null;
while (true) {
fileName = input.nextLine();
file = new File(fileName);
if (file.isFile()) {
System.out.println(file + " already exists! Please try again:");
}
else {
break;
}
}
FileWriter writer = new FileWriter(file);
}
}

How to use try/catch to avoid throwing FileNotFoundException in java

I am trying to output a file scanner object from my method. This is a school assignment and I am specifically instructed to NOT throw any exceptions, but use try/catch instead. The assignment requires that the command line prompt the user for a file to scan. If the file does not exist, we are supposed to tell the user, then prompt them for a file again. If the file does exist, then the method returns a scanner object that scans the file.
My code works, but it is not clean. It involves 2 methods. This is my code so far:
public static Scanner getInputScanner (Scanner console) {
File inputFile = null;
Scanner input = null;
try {
inputFile = getFile(inputFile, console);
input = new Scanner (inputFile);
return input;
} catch (FileNotFoundException e) {
try {
return input = new Scanner (getFile (inputFile, console));
} catch (FileNotFoundException f) {
System.out.println("An error has occured.");
return input;
}
}
}
public static File getFile (File inputFile, Scanner console) {
System.out.println("Enter input file: ");
inputFile = new File (console.nextLine());
while (!inputFile.exists()) {
System.out.println("File does not exist.");
System.out.print("Enter input file: ");
inputFile = new File (console.nextLine());
}
return inputFile;
}
The problem with the code is that the output looks like this:
Enter input file:
File does not exist.
Enter input file:
It then is waiting for the user's input. I don't want the output to have the 2 lines of code before the last line though.
Can anybody explain why my code is outputting these 2 lines?
Also, is there a simpler solution to getting an input file without throwing the FileNotFoundException?
Thanks!
If I understand correctly,
your program outputs these lines when you run it,
no matter what,
without you getting a chance to actually enter a filename.
Enter input file:
File does not exist.
And then the programs asks you again:
Enter input file:
And you don't want the first two lines above, right?
This can happen for example if the Scanner console you received has an unread newline in it.
You haven't posted that part of the code,
so it's hard to tell, but this is a common gotcha with Scanner.
Before calling getInputScanner,
make sure the Scanner console is ready to use,
with no unread garbage still buffered in it.
As for the second part of your question,
yes this can be written simpler and better, for example:
public static Scanner getInputScanner(Scanner console) {
try {
File inputFile = getExistingFile(console);
return new Scanner(inputFile);
} catch (FileNotFoundException e) {
throw new AssertionError("The file is expected to exist (was supposed to be verified earlier)");
}
}
public static File getExistingFile(Scanner console) {
while (true) {
System.out.println("Enter input file: ");
File inputFile = new File(console.nextLine());
if (inputFile.exists()) {
return inputFile;
}
System.out.println("File does not exist.");
}
}
It execute below line as soon the getFile() being called.
System.out.print("Enter input file: ");
Since no file exist, the below lines keeps on executing :
while (!inputFile.exists()) {
System.out.println ("File does not exist.");
System.out.print("Enter input file: ");
You can use throws() instead of try/catch, then caller will take care of exception.
Had to consume whatever junk was being carried over from the scanner by inserting a Scanner.nextLine() before getting user input. Final code looks like this:
public static Scanner getInputScanner(Scanner console) {
try {
File inputFile = getExistingFile(console);
return new Scanner(inputFile);
} catch (FileNotFoundException e) {
throw new AssertionError("The file is expected to exist (was supposed to be verified earlier)");
}
}
public static File getExistingFile(Scanner console) {
while (true) {
console.nextLine();
System.out.println("Enter input file: ");
File inputFile = new File(console.nextLine());
if (inputFile.exists()) {
return inputFile;
}
System.out.println("File does not exist.");
}
}

How do I resolve these exceptions?

To be fair, I'm not getting these exceptions but merely trying to find a away to cover these exceptions. The exceptions are NosuchElementException and NumberFormatException.
Note: This programs works perfectly because the txt file is fine. However, introduce anything that is not a number and it will fail.
Here is the main class where the problem could occur:
BankReader.java
package bankreader;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class BankReader
{
public static void main(String[] args)
{
BankReader reader = new BankReader();
Scanner scan = new Scanner(System.in);
String fileName = "";
boolean finished = false;
while(!finished)
{
try
{
System.out.print("Enter the name of the file: ");
fileName = scan.nextLine();
scan = reader.checkFile(fileName, scan);
reader.readFile(scan);
finished = true;
}
catch(IOException ex)
{
System.out.print("\nThis file does not exist or had");
System.out.println(" characters that were not numbers. Please enter a different file.\n");
}
}
scan.close();
}
public Scanner checkFile(String fileName, Scanner scan) throws IOException
{
File file = new File(fileName);
scan = new Scanner(file);
return scan;
}
public void readFile(Scanner scan)
{
String accountNumber = "";
double accountBalance = -1;
Bank bank = new Bank();
while(scan.hasNext())
{
accountNumber = scan.next();
accountBalance = Double.parseDouble(scan.next());
BankAccount bankAccount = new BankAccount(accountNumber, accountBalance);
bank.addAccount(bankAccount);
}
if (bank.numberOfAccounts() > 0)
{
BankAccount maxBalance = bank.getHighestBalance();
System.out.println(maxBalance.getAccountNumber() + ": " + "$" + maxBalance.getBalance());
}
else
System.out.println("\nThe file had no accounts to compare.");
}
}
Here is the txt file I'm working with:
346583155444415 10000.50
379611594300656 5000.37
378237817391487 7500.15
378188243444731 2500.89
374722872163487 25000.10
374479622218034 15000.59
342947150643707 100000.77
So even though this is my own txt file, what if I was accessing a text file that a character that wasn't a number or had an account number but no balance and vice versa. I would like to know how I can deal with these exceptions.
What I've tried:
I've tried to do scan.nextLine() to move away from the exception but it just introduces another exception.
I've also tried to use a method that uses regex to check if the string is a number. The problem is I'm using a variable that is not a string and I would rather not create more checks.
It seems to me that no more what I do, I can't recover my scanner after an exception has occurred.
before parsing you can test if it is a double with scan.hasNextDouble and parse or read the number only then else you set default value and move next by reading the incorrect value and dont do anything with it

Searching through a text file java

So I am trying to search through a text file and if the user input is found, it returns the entire sentence including white spaces.But apparently I only get the first string and nothing pass the first string in the sentence. For example if i have a text file called "data.txt" and the contents in the first line is " I am a legend". after user enters "I am a legend" the output after the file is searched is "I". Any help would be appreciated.
public static void Findstr() { // This function searches the text for the string
File file = new File("data.txt");
Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();
Scanner scanner;
try {
scanner = new Scanner(file).useDelimiter( ",");
while (scanner.hasNext()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(name)) {
// a match!
System.out.println("I found " + name);
break;
}
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
package com.example;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileSearch {
public void parseFile(String fileName,String searchStr) throws FileNotFoundException{
Scanner scan = new Scanner(new File(fileName));
while(scan.hasNext()){
String line = scan.nextLine().toLowerCase().toString();
if(line.contains(searchStr)){
System.out.println(line);
}
}
}
public static void main(String[] args) throws FileNotFoundException{
FileSearch fileSearch = new FileSearch();
fileSearch.parseFile("src/main/resources/test.txt", "am");
}
}
test.txt contains:
I am a legend
Hello World
I am Ironman
Output:
i am a legend
i am ironman
The above code does case insensitive search. You should use nextLine() to get the complete line. next() breaks on whitespaces.
Reference:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
Scanner.next(); returns the next caracter instead use Scanner.readLine();
Edit:
Belive Scanners use .nextLine(); not .readLine();
When you are scanning your input..
Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();
You are accepting only one token. You should accept whole line to be searched as your token using kb.nextLine()

Categories

Resources