read from text file using try/catch blocks - java

so im trying to read from a file the number of words and adding them up to give and int answer? And help and or suggestions would be nice, and i can only use a try/catch while for loop and if/else/if.... Thanks!
Here what i got so far:
package filereadingexercise2;
import java.io.*;
import java.util.Scanner;
/**
*
* #author theGreggstar
*/
public class FileReadingExercise2
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner keys = new Scanner(System.in);
String nameOfFile;
System.out.print("Please Enter The Name Of A File Or Directory, or Type Quit To Exit: ");
nameOfFile = keys.nextLine();
Scanner input = null;
try
{
input = new Scanner(new File(nameOfFile));
}
catch(FileNotFoundException s)
{
System.out.println("File does Not Exist Please Try Again: ");
}
while(input.hasNext())
{
String contents = input.next();
int length;
System.out.print(contents);
}
}
}

If I understand you correctly, you want something like this -
public static void main(String[] args) {
Scanner keys = new Scanner(System.in);
for (;;) { // Loop forever.
System.out.print("Please Enter The Name Of A File Or "
+ "Directory, or Type Quit To Exit: ");
String nameOfFile = keys.nextLine().trim(); // get the User input.
if (nameOfFile.equalsIgnoreCase("quit")) { // check for exit condition.
break;
}
File f = new File(nameOfFile); // Construct a File.
if (f.exists()) { // Does it exist?
if (f.isFile() && f.canRead()) { // is it a File and can I read it?
Scanner input = null;
try {
input = new Scanner(f); // The Scanner!
while (input.hasNextLine()) {
String contents = input.nextLine();
System.out.println(contents); // Print the lines.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (input != null) {
input.close(); // Close the file scanner.
}
}
} else if (f.isDirectory()) { // No, it's a directory!
try {
System.out.println("File "
+ f.getCanonicalPath()
+ " is a directory");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Related

Call the exact value from text File

Hi guys need help for my mini project for schools. How do i compare the user input and match to my database in text file. this is like validity for username and password. I want to call the second line on my data base using account Number and pin.
this is my data base.
0,admin,adminLastName,123456,123456
1,user,userLastName,1234567,123456
0 = id
admin = name
adminLastName = Last Name
1234567 = accountNumber
123456 = pin
and this is my code.
package atm;
import java.io.File;
import java.util.Scanner;
public class Login {
static void verifyLogin(String name, String lastName, String userAccountNumber, String userPin, String filePath){
Scanner inputData = new Scanner(System.in);
boolean isFound = false;
String tempAccountNumber = "";
String tempPin = "";
System.out.print("\nAccount Number: ");
userAccountNumber = inputData.next();
System.out.print("\nPIN: ");
userPin = inputData.next();
try{
Scanner readTextFile = new Scanner(new File("myDataBase.txt")).useDelimiter("[,\n]");
while (readTextFile.hasNext() && !isFound){
tempAccountNumber = readTextFile.next();
tempPin = readTextFile.next();
if (tempAccountNumber.trim().equals(userAccountNumber.trim()) && tempPin.trim().equals(userPin.trim())){
isFound = true;
System.out.println("Welcome " + name+ " " +lastName);
System.out.println("\nLogin Successfully!");
}
else {
System.out.println("You have entered your PIN or ACCOUNT NUMBER incorrectly. Please check your PIN or ACCOUNT NUMBER and try again.\n If you don't have account yet please go to SignUp page!\n");
myMain mainMenu = new myMain();
mainMenu.inputKeyboard();
}
}
readTextFile.close();
}
catch (Exception e){
}
inputData.close();
}
}
If your textfile contains 1 user per line, and you split it with ',' then you can take each line like you do, then split that line into a string[] array and check if i.e. the name corresponds to 'admin'.
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Boolean loggedin = false;
String fileName = "accounts.txt";
String line = null;
System.out.println("What's your username?");
String tempUsername = input.nextLine();
System.out.println("What's your password?");
String tempPassword = input.nextLine();
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
String[] currAccount = line.split(",");
if (currAccount[1].equals(tempUsername) && currAccount[4].equals(tempPassword)) {
loggedin = true;
System.out.println("You have successfully logged in!");
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
ex.printStackTrace();
// Let's create it if file can't be found or doesn't exist, but let's ask first.
String answer;
System.out.print("File not found, do you want to create it? [Y/n]: ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("y")) {
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("File has been created!");
} catch (IOException exc) {
exc.printStackTrace();
}
} else {
System.out.println("File was not created!");
}
}
catch(IOException ex) {
ex.printStackTrace();
}
if (!loggedin) {
System.out.println("Your login combination did not exist.");
}
}
}
Please note, I haven't commented a lot, but it should still make sense.
After splitting remember that you start at array index 0, and not 1. So at index 1 the name on the account will be.
Goodluck.

How to read from a text file and move onto next line

I am making a program that will scan a text file to find all the ints, and then print them out, and move onto the next line
Ive tried turning if statements into while loops to try to improve, but my code runs through the text file, writes out all the numbers, but fails at the end where it runs into a java.util.NoSuchElementException. If I have a text file with the numbers
1 2 3
fifty 5,
then it prints out
1
2
3
5
But it crashes right at the end everytime
import java.util.Scanner;
import java.io.*;
public class filterSort
{
public static void main()
{
container();
}
public static void run()
{
}
public static void container()
{ Scanner console = new Scanner(System.in);
int count = 0;
int temp;
try
{
System.out.print("Please enter a file name: ");
String fileName = console.nextLine();
Scanner file = new Scanner(new File(fileName));
while(file.hasNextLine())
{
while(file.hasNextInt())
{
temp = file.nextInt();
System.out.println(temp);
}
file.next();
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
}
}
}
Replace
file.next();
with
if(file.hasNextLine())
file.nextLine();
Every time you try to advance on a scanner, you must check if it has the token.
Below is the program which is working for me . Also it is good practice to close all the resources once done and class name should be camel case. It's all good practice and standards
package com.ros.employees;
import java.util.Scanner;
import java.io.*;
public class FileTest
{
public static void main(String[] args) {
container();
}
public static void container()
{ Scanner console = new Scanner(System.in);
int count = 0;
int temp;
try
{
System.out.print("Please enter a file name: ");
String fileName = console.nextLine();
Scanner file = new Scanner(new File(fileName));
while(file.hasNextLine())
{
while(file.hasNextInt())
{
temp = file.nextInt();
System.out.println(temp);
}
if(file.hasNextLine())
file.next();
}
file.close();
console.close();
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
}
}
}

File Input and output method issues

So my program is supposed to say what type of a token it is from my input file. My second method is supposed to write whatever input from the keyboard to an output file until the user types stop. The problem is my first method won't output the integers to their right type. My second method will only put stop in the output file. Here is my code. Any help would be much appriciated.
public class R16 {
public void readFile(String inputFile) {
try {
File in = new File(inputFile);
Scanner scan = new Scanner(in);
while (scan.hasNext()) {
if (scan.hasNextInt()) {
System.out.println("Integer: " + scan.nextInt());
}
if (scan.hasNext()) {
System.out.println("String: " + scan.next());
}
if (scan.hasNextDouble()) {
System.out.println("Double: " + scan.nextDouble());
}
}
scan.close();
} catch (IOException e) {
System.out.println("Error, not good");
}
}
public void writeFile(String outputFile) {
try {
File out = new File(outputFile);
PrintWriter w = new PrintWriter(out);
Scanner scan= new Scanner(System.in);
System.out.print("Enter Text: ");
while(!scan.next().equals("stop")){
w.print(scan.next());
}
w.close();
scan.close();
} catch (IOException e) {
System.out.println("Error, it just got real");
}
}
public static void main(String[] args) {
R16 test = new R16();
test.readFile(args[0]);
test.writeFile(args[1]);
}
}
In your loop, you check for stop then throw away all input.
while(!scan.next().equals("stop")){
Try using something like
String input;
while (!(input = scan.next()).equals("stop")) {
w.print(input);
Now within the loop, you have access to the input variable which contains the input string.

How do you get past an exception with FileReader

I'm trying to get the user to input their file name. If the file name is valid it passes through. However, if the file name is invalid then its suppose to ask the user again for a file. If a purposely enter an invalid file name, the program doesn't get past the exception branch.
Here's the code:
public class LineNumbers {
private static Scanner getFile() {
Scanner in = new Scanner(System.in);
Scanner scannedFile = new Scanner(System.in);
String inputFile;
boolean validFile = false;
while (!validFile) {
try {
System.out.print("Enter your file name: ");
inputFile = in.nextLine();
scannedFile = new Scanner(new FileReader(inputFile));
validFile = true;
} catch (Exception e) {
System.out.print(e);
System.out.print("Invalid File");
in.next();
scannedFile.next();
}
}
return scannedFile;
}
public static void main(String[] args) {
String word = getFile().nextLine();
}
}
Do are getting problems when calling in.next(); and scannedFile.next(); in catch block. You have already expected in.readLine() if invalid user input occurred. Additionally you should understand that the scannedFile is reachable, that's why got the exception. So you cannot use scannedFile.next(); in the catch block also.
Do following modifications
private static Scanner getFile() {
Scanner in = new Scanner(System.in);
Scanner scannedFile = new Scanner(System.in);
String inputFile;
boolean validFile = false;
while (!validFile) {
try {
System.out.print("Enter your file name: ");
inputFile = in.nextLine();
scannedFile = new Scanner(new FileReader(inputFile));
validFile = true;
} catch (Exception e) {
System.out.println(e);
System.out.println("Invalid File");
//no scanned file, input file could not find
scannedFile = null;
//file was not valid
validFile = false;
}
}
return scannedFile;
}

Main method input file keeps giving me IndexOutOfBoundsException (even with right arguments)

I'm trying to use args[0] as an input file, but when I run the program, I keep getting an IndexOutOfBoundsException, although I'm quite sure that args[0] is the correct argument. I ran into this problem with my last program as well, but I can't figure out what I'm doing wrong.
Code:
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class SortTest {
public static void main(String args[]) throws FileNotFoundException {
try {
Scanner read = new Scanner(new File(args[0]));
while (read.hasNextLine()) {
String name = read.nextLine();
read.nextLine();
String line1 = read.nextLine();
int sh = Integer.parseInt(line1.substring(0,2));
int sm = Integer.parseInt(line1.substring(3));
read.nextLine();
String line2 = read.nextLine();
int fh = Integer.parseInt(line2.substring(0,2));
int fm = Integer.parseInt(line2.substring(3));
if (fh<sh) {
System.out.println("Times not in correct order.");
return;
} else if (fh==sh) {
if (fm<sm) {
System.out.println("Times not in correct order.");
return;
}
} else {
System.out.println(name + "\n" + sh + ":" + sm + "\n" + fh + ":" + fm);
}
}
read.close();
}
catch (FileNotFoundException e) {
System.out.println("Invalid file path.");
}
catch (NoSuchElementException n) {
System.out.println("No readable text in file.");
}
catch (IndexOutOfBoundsException x) {
System.out.println("Proper format is java LectureSortTest <input>");
}
catch (NumberFormatException num) {
System.out.println("File contents not formatted correctly");
}
}
}

Categories