Scanner will take user input but will not find the file - java

This is a program to read a file and print out the file with some of the text edited. The code will compile the issue is that it will read the users input but will say file is not found when the file is there. I feel like I am missing something. I am brand new at this so go easy on me.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MainTest {
public static void main(String args[]) {
// if (args[0] != null)
readFile();
}
public static void readFile() { // Method to read file
Scanner inFile = null;
String out = "";
try {
Scanner input = new Scanner(System.in);
System.out.println("enter file name");
String filename = input.next();
File in = new File(filename); // ask for the file name
inFile = new Scanner(in);
int count = 0;
while (inFile.hasNextLine()) { // reads each line
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
out = out + ch;
if (ch == '{') {
count = count + 1;
out = out + " " + count;
} else if (ch == '}') {
out = out + " " + count;
if (count > 0) {
count = count - 1;
}
}
}
}
System.out.println(out);
} catch (FileNotFoundException exception) {
System.out.println("File not found.");
}
inFile.close();
}
}

You can use System.getProperty("user.dir") to find where Scanner looking to find your file. And you should be sure your file is located here.

Related

Why my Java program works perfectly in windows but it's a disaster in linux?

I wrote a program that reads a text file, deletes the requested string and rewrites it without the string. This program takes three arguments from the terminal: 1) the input file 2) the string 3) the output file.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
class wordfilter {
public static void main(String[] args) {
Scanner scanner = new Scanner("");
Scanner conteggio = new Scanner("");
int numel = 0;
File file = new File(args[0]); // Argomento 0: il file
try {
conteggio = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (conteggio.hasNext()) {
numel++;
conteggio.next();
}
conteggio.close();
String[] lettura = new String[numel];
int i = 0;
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
System.out.println("Contarighe -> " + numel);
for (i = 0; i < lettura.length; i++) {
System.out.println("Elemento " + i + " - > " + lettura[i]);
}
scanner.close();
String escludi = args[1]; // Argomento 1: il filtro
String[] filtrato = rimuovi(escludi, lettura);
if (args.length == 3) stampaSuFile(filtrato, args[2]);
}
public static String[] rimuovi(String esclusione, String[] input) {
String[] nuovoV;
String escludi = esclusione;
int dim = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi))
dim++;
}
nuovoV = new String[dim];
int j = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi)) {
nuovoV[j] = input[i];
j++;
}
;
}
return nuovoV;
}
public static void stampaSuFile(String[] out, String path) {
String closingstring = "";
File destinazione = new File(path);
try {
destinazione.createNewFile();
} catch (IOException e) {
System.out.println("Errore creazione file");
}
try {
FileWriter writer = new FileWriter(destinazione);
for (int i = 0; i < out.length; i++)
writer.write(out[i] + (i == (out.length-1) ? closingstring : " "));
writer.close();
System.out.println("Scrittura eseguita correttamente");
} catch (IOException e) {
System.out.println("Errore scrittura file");
}
}
}
On Windows no problem, it works perfectly.
On Linux instead when i write something like java wordfilter in.txt word out.txt
I get
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at wordfilter.main(wordfilter.java:42)
What's the problem? It's because of some difference on linux?
You're mixing line and token based functions, :hasNextLine() and next(). If the input ends with a line feed (typical on Linux) hasNextLine returns true at the end of the file, but there is no next "item".
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
You should use either hasNext with next, or hasNextLine with nextLine, mixing them is confusing.
while (scanner.hasNext()) {
lettura[i] = scanner.next();
i++;
}
The input file ends in a newline on Linux. Therefore, there's another line, but it's empty. If you remove the final newline from the input, the program will start working normally.
Or, import the exception
import java.util.NoSuchElementException;
and ignore it int the code
while (scanner.hasNextLine()) {
System.out.println("" + i);
try {
lettura[i] = scanner.next();
} catch (NoSuchElementException e) {}
i++;
}

I'm getting FileNotFound exception while trying to create a file

I'm trying to prompt the user to input the name a file they'd like to write to, create that .txt file and then write the qualifying lines of text into that file and save it. inside the do while, it seems to be skipping over the user input for the name of the file they'd like to save to, looping back around and then getting a FileNotFoundException, and it shouldn't even be looking for a file.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you
would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
do {
System.out.println("please enter a name for the file to write to
(end with .txt): ");
String out = user.nextLine(); //PROBLEM HERE! SKIPS USER INPUT
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0],
Integer.parseInt(elements[1]),
Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]),
Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost &&
bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I just needed to skip a line before the loop began.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
user.nextLine(); //SOLUTION HERE
do {
System.out.println("please enter a name for the file to write to (end with .txt): ");
String out = user.nextLine();
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0], Integer.parseInt(elements[1]), Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]), Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost && bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}

Increase all characters by 1 (JAVA)

So I need help with increasing all characters in a file. Whole file is able to read and get all the info form the user but when it comes to actual increasing all characters from (this case) a file it just outputs a blank file.
Goal of this program is to read in a users file get all the text from the file and increase or decrease the letters by one. So A is now a B or B is now a C or via versa B is now a A or C is now a B. When it goes to export/close the file it just is blank.
Here is that portion of the code:
while (fileIn.hasNext())
{
letter.add(fileIn.next());
for (int i = letter.size() - 1; i >= 0; i--)
{
ch = letter.get(i).charAt(0);
ch--;
fileout1.println(ch);
}
//Makes a new line at end of line
System.out.println();
}
Whole code is as follows:
import java.util.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.util.ArrayList;
public class Assignment9
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
Scanner fileIn;
File f;
char ch = 65;
String fileName = "";
boolean userA = false;
String usersChoice = "";
ArrayList<String> letter = new ArrayList<String>();
try
{
System.out.println("Please enter the file name that you would like encrypted/decrypted: ");
fileName = in.nextLine();
//Builds the file and attaches the Scanner
f = new File (fileName);
fileIn = new Scanner (f);
PrintWriter fileout1 = new PrintWriter ("decrypt.txt");
PrintWriter fileout2 = new PrintWriter ("encrypt.txt");
System.out.println("Would you like to Decrypt or Encrypt the file?");
usersChoice = in.nextLine();
userA = true;
//Loop through the file and translate the characters
if (usersChoice.equalsIgnoreCase("Decrypt"))
{
while (fileIn.hasNext())
{
letter.add(fileIn.next());
for (int i = letter.size() - 1; i >= 0; i--)
{
ch = letter.get(i).charAt(0);
ch--;
fileout1.println(ch);
}
//Makes a new line at end of line
System.out.println();
}
//Decrease every letter by 1 (runs backwords)
System.out.println("Decrypt.txt has been created.");
fileout1.close();
}
//encrypts the file by increasing by 1
if (usersChoice.equalsIgnoreCase("encrypt"))
{
while (fileIn.hasNext())
{
letter.add(fileIn.next());
}
//Decrease every letter by 1 (runs backwords)
for (int i = letter.size() -1; i >= 0; i--)
{
System.out.println(letter);
ch --;
}
System.out.println("Encrypted.txt has been created.");
fileout2.close();;
}
} //end of try
catch (FileNotFoundException e)
{
System.out.println("Sorry invalid file, please try again");
fileName = in.nextLine();
}
} // end of main
} //end of program
You can do something like as below,
FileReader fr = null;
FileWriter fw = null;
int c;
try {
fr = new FileReader("C:\\Zia\\test.txt");
fw = new FileWriter("C:\\Zia\\Result.txt");
while ((c = fr.read()) != -1) {
if(c!=32)
fw.write((char)--c);
else
fw.write((char)c);
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
My test.txt file contains the below content,
Hello How are you doing.
and result.txt contains the below result after decreasing the char by one.
Gdkkn Gnv `qd xnt cnhmf-
you may interchange the file name for both the file for Reader and writer and increase the char by 1 to verify the decryption.

Character Count

I'm trying to count the number of Words, Lines and characters(excluding whitespace). The only part I can't get to work is ignoring the whitespace for the character count.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Exercise2 {
public static void main(String[] args) throws IOException{
File file = getValidFile();
int count = wordCount(file);
int lines = lineCount(file);
int characters = characterCount(file);
System.out.println("Total Words = " + count);
System.out.println("Total Lines = " + lines);
System.out.println("Total Characters = " + characters);
}
public static int characterCount(File file) throws IOException {
{
Scanner inputFile = new Scanner(file).useDelimiter(",\\s*");;
int characters = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.next(); //read in a word
characters++; //count the word
}
inputFile.close();
return characters;
}
}
public static int lineCount(File file)throws IOException {
{
Scanner inputFile = new Scanner(file);
int lines = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.nextLine(); //read in a line
lines++; //count the line
}
inputFile.close();
return lines;
}
}
public static int wordCount(File file) throws IOException {
{
Scanner inputFile = new Scanner(file);
int count = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.next(); //read in a word
count++; //count the word
}
inputFile.close();
return count;
}
}
public static File getValidFile()
{
String filename; // The name of the file
File file;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get a valid file name.
do
{
/*for (int i = 0; i < 2; i ++ )
{*/
System.out.print("Enter the name of a file: ");
filename = keyboard.nextLine();
file = new File(filename);
if (!file.exists())
System.out.println("The specifed file does not exist - please try again!");
}while( !file.exists());
return file;
}
}
If you want to count the characters in the file, excluding any whitespace, you can read your file line by line and accumulate the character count, or read the whole file in a String and do the character count, e.g.
String content = new Scanner(file).useDelimiter("\\Z").next();
int count = 0;
for (int i = 0; i < content.length(); i++) {
if (!Character.isWhitespace(content.charAt(i))) {
count++;
}
}
System.out.println(count);
EDIT
Other solutions if you don't care about the content of the file, then there is no need to load it into a String, you can just read character by character.
Example counting the non-whitespace characters in Arthur Rimbaud poetry.
Using a Scanner
URL rimbaud = new URL("http://www.gutenberg.org/cache/epub/29302/pg29302.txt");
int count = 0;
try (BufferedReader in = new BufferedReader(new InputStreamReader(rimbaud.openStream()))) {
int c;
while ((c = in.read()) != -1) {
if (!Character.isWhitespace(c)) {
count++;
}
}
}
System.out.println(count);
Using a plain StreamReader
count = 0;
try (Scanner sin = new Scanner(new BufferedReader(new InputStreamReader(rimbaud.openStream())))) {
sin.useDelimiter("");
char c;
while (sin.hasNext()) {
c = sin.next().charAt(0);
if (!Character.isWhitespace(c)) {
count++;
}
}
}
System.out.println(count);

Reading file line by line and print

I'm trying to write a program that takes the file name from the user (for example: English), then opens this file and prints (9 questions) divided on (3 levels, each level has 3 questions), then opens another file (EnglishC) that contains the answers and then compares it with the correct answer. if correct grade++.
Output:
enter your choice:
1.English
2.Math
3.Science
java.io.FileNotFoundException: English.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at Generater.createQuestions(Generater.java:50)
at Generater.choose_subject_And_Level(Generater.java:41)
at Generater.main(Generater.java:139)
Source:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Generater {
static int levelNo = 1;
static int subjectName;
static int grade;
static String fileName;
static String fileNameCorrect;
static String ans;
static String correctAns;
public static void choose_subject_And_Level() {
// here the main will call this method to ask the user what subject to be tested in?
Scanner input = new Scanner(System.in);
System.out.println("enter your choice:\n 1.English\n2.Math\n3.Science ");
subjectName = input.nextInt();
switch (subjectName) {
case 1:
fileName = "English.txt";
fileNameCorrect = "EnglishC.txt";
break;
case 2:
fileName = "Math.txt";
fileNameCorrect = "MathC.txt";
break;
case 3:
fileName = "Science.txt";
fileNameCorrect = "SienceC.txt";
break;
}
createQuestions(fileName, fileNameCorrect, levelNo);
}
public static void createQuestions(String fileName, String fileNameCorrect,
int levelNo) {
Scanner input, input2;
try {
input = new Scanner(new File(fileName));
input2 = new Scanner(new File(fileNameCorrect));
input.useDelimiter("*");
FileInputStream fs = new FileInputStream(fileName);
FileInputStream fs2 = new FileInputStream(fileNameCorrect);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
BufferedReader br2 = new BufferedReader(new InputStreamReader(fs2));!
while (input.hasNext()) {
switch (levelNo) {
case 1:
for (int i = 1,k=1; i <= 3 ; i++,k++) {
System.out.printf("\nQ#\f: " + input.next() + "\n" , k);
ans = input.next();
correctAns = input2.next();
if (ans == correctAns) {
grade++;
}
}
break;
case 2:
for (int i = 4, k = 1; i <= 6; i++, k++) {
try {
for (int j = 1; j <= 3; j++) {
br.readLine();
correctAns = br2.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.printf("\nQ#\f: " + input.next() + "\n" , k);
ans = input.next();
if (ans == correctAns) {
grade++;
}
}
break;
case 3:
for (int i = 7, k = 1; i <= 9; i++, k++) {
try {
for (int j = 1; j <= 6 ; j++){
br.readLine();
correctAns = br2.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.printf("\nQ#\f: " + input.next() + "\n" , k);
ans = input.next();
correctAns = input2.next();
if (ans == correctAns) {
grade++;
}
}
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// the main
public static void main(String[] args) {
choose_subject_And_Level();
}
}
When java.io.FileNotFoundException is thrown it means the file that is supposed to be read/written is not present at the location specified. Look where you have the file on the filesystem and confirm that the file in question (English.txt) is present.
More info here: https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html

Categories

Resources