on one of my Java homework assignments, I am asked to request 2 file names from a user, copy all the text from the first file, and then convert it all to uppercase letters and write it to the second file.
I have my reading and writing methods copied almost exactly as it is in my book, but I can not compile because I am getting the error that the file is not found. I have even tried removing the part where the user assigns the file names and just added the directory and file location myself but I am still getting the FileNotFound Exception.
The errors appear on lines 17 and 32.
Is there something I am doing wrong or is there a problem with Netbeans?
import java.io.*;
import java.util.Scanner;
public class StockdaleUpperfile {
public static void main(String[] args) {
String readFile, writeFile, trash;
String line, fileContents, contentsConverted;
System.out.println("Enter 2 file names.");
Scanner keyboard = new Scanner(System.in);
readFile = keyboard.nextLine();
writeFile = keyboard.nextLine();
File myFile = new File(readFile);
Scanner inputFile = new Scanner(myFile); //unreported exception FileNotFoundException; must be caught or declared to be thrown;
line = inputFile.nextLine();
fileContents=line;
while(inputFile.hasNext())
{
line = inputFile.nextLine();
fileContents+=line;
}
inputFile.close();
contentsConverted = fileContents.toUpperCase();
PrintWriter outputfile = new PrintWriter(writeFile); //Isn't this supposed to create a file if it doesn't detect one?
outputfile.println(contentsConverted);
outputfile.close();
}
}
}
Change the method as
public static void main(String[] args) throws Exception
Related
I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.
I am getting the following error messages:
java.io.FileNotFoundException: 10_Random (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at insertionSort.main(insertionSort.java:14)
I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You have to put file extension here
File file = new File("10_Random.txt");
Use following codes to read the file
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
-> This application is printing the file content line by line
here are some working and tested methods;
using Scanner
package io;
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
public static void main(String[] args) throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Here's another way to read entire file (without loop) using Scanner class
package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
using BufferedReader
package io;
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
BufferedReader br=new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine())!=null){
System.out.println(st);
}
}
}
using FileReader
package io;
import java.io.*;
public class ReadingFromFile {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
int i;
while((i=fr.read())!=-1){
System.out.print((char) i);
}
}
}
Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).
Use the Class.getResource method to locate your file in the classpath - don't rely on the current directory:
URL url = insertionSort.class.getResource("10_Random");
File file = new File(url.toURI());
Specify the absolute file path via command-line arguments:
File file = new File(args[0]);
In Eclipse:
Choose "Run configurations"
Go to the "Arguments" tab
Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section
No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.
for (int i =0 ; sc.HasNextLine();i++)
{
array[i] = sc.NextInt();
}
Something to this effect will keep setting values of the array to the next integer read.
Than another for loop can display the numbers in the array.
for (int x=0;x< array.length ; x++)
{
System.out.println("array[x]");
}
You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.
private void loadData() {
Scanner scanner = null;
try {
scanner = new Scanner(new File(getFileName()));
while (scanner.hasNextLine()) {
Scanner lijnScanner = new Scanner(scanner.nextLine());
lijnScanner.useDelimiter(";");
String stadVan = lijnScanner.next();
String stadNaar = lijnScanner.next();
double km = Double.parseDouble(lijnScanner.next());
this.voegToe(new TweeSteden(stadVan, stadNaar), km);
}
} catch (FileNotFoundException e) {
throw new DbException(e.getMessage(), e);
} finally {
if(scanner != null){
scanner.close();
}
}
}
File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file.
Please log the file.getAbsolutePath() to verify that file is correct.
You should use either
File file = new File("bin/10_Random.txt");
Or
File file = new File("src/10_Random.txt");
Relative to the project folder in Eclipse.
The file you read in must have exactly the file name you specify: "10_random" not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.
Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.
At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.
you must use a file name by it's extension in File object constructor, as an example:
File myFile = new File("test.txt");
but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:
Scanner sc = new Scanner(Paths.get("test.txt"));
in this way you must import java.nio.file.Paths as well.
I am creating a CSV parser library in Java. I have the following code so far:
However I keep getting the error when I try to include user input to the ("Enter a delimiter") part:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at demo.CSV.main(CSV.java:19)
Also can you please help me figure out how I would create a test application that can use the library.
Thank you.
package demo;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CSV {
public static void main(String[] args) throws FileNotFoundException {
Scanner x = new Scanner(System.in);
System.out.println("Enter the File");
String s = x.next();
x.close();
Scanner scanner = new Scanner(new File(s));
scanner.useDelimiter(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
System.out.println("Enter delimiter");
Scanner scanner1 = new Scanner(System.in);
String format = scanner1.nextLine();
while(scanner.hasNext()){
System.out.println(scanner.next()+format);
}
scanner.close();
}
}
The problem boils down to the fact that you're not using Scanner.nextLine() properly, compounded by the fact that your input file is empty.
When you use nextLine(), you need to enclose it within a loop that checks to see if an input source has a next line using hasNextLine() before trying to read the line with nextLine().
Your code assumes that there's a next line without first checking. Meanwhile, your input file is empty, so you get NoSuchElementException.
Instead of going in blind like this:
String format = scanner1.nextLine();
Replace that line with this:
String format = null;
while(scanner1.hasNext())
{
format = scanner1.nextLine();
}
Then make sure you generate an input file that actually has one or more lines in it.
Following is my code that I am working on for a school project. It does ok up until I try to read the animal.txt file. Can someone please tell me what I am doing wrong? I am attaching my compilation error as an image. Thanks in advance.
[input error image1
package finalproject;
//enabling java programs
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.FileInputStream;
import java.io.IOException;
public class Monitoring {
public static void choseAnimal() throws IOException{
FileInputStream file = null;
Scanner inputFile = null;
System.out.println("Here is your list of animals");
file = new FileInputStream("\\src\\finalproject\\animals.txt");
inputFile = new Scanner(file);
while(inputFile.hasNext())
{
String line = inputFile.nextLine();
System.out.println(line);
}
}
public static void choseHabit(){
System.out.println("Here is your list of habits");
}
public static void main(String[] args) throws IOException{
String mainOption = ""; //user import for choosing animal, habit or exit
String exitSwitch = "n"; // variable to allow exit of system
Scanner scnr = new Scanner(System.in); // setup to allow user imput
System.out.println("Welcome to the Zoo");
System.out.println("What would you like to monitor?");
System.out.println("An animal, habit or exit the system?");
mainOption = scnr.next();
System.out.println("you chose " + mainOption);
if (mainOption.equals("exit")){
exitSwitch = "y";
System.out.println(exitSwitch);
}
if (exitSwitch.equals( "n")){
System.out.println("Great, let's get started");
}
if (mainOption.equals("animal")){
choseAnimal();
}
if (mainOption.equals("habit")) {
choseHabit();
}
else {
System.out.println("Good bye");
}
}
}
\\src\\finalproject\\animals.txt suggests that the file is an embedded resource.
First, you should never reference src in you code, it won't exist once the program is built and package.
Secondly, you need to use Class#getResource or Class#getResourceAsStream in order to read.
Something more like...
//file = new FileInputStream("\\src\\finalproject\\animals.txt");
//inputFile = new Scanner(file);
try (Scanner inputFile = new Scanner(Monitoring.class.getResourceAsStream("/finalproject/animals.txt"), StandardCharsets.UTF_8.name()) {
//...
} catch (IOException exp) {
exp.printStackTrace();
}
for example
Now, this assumes that file animals.txt exists in the finalproject package
The error message clearly shows that it can't find the file. This means there's two possibilities:
File does not exist in the directory you want
Directory you want is not the directory you have.
I would start by creating a File object looking at "." (current directory) to and printing that to see what directory it looks by default. You may need to hard code the file path, depending on what netbeans is using for a default directory.
So i am working on a code that receives 2 strings. The string are "input#.txt" or "output#.txt" the # symbol is replaced with whatever number file is used. Now in the input file is the information I need to get to. How do I determine if that input.txt file can be opened and how do I open it.
I've tried a buffered reader and trying to just make the string a file.
import java.util.*;
import java.io.*;
public class Robot {
public static void readInstructions(String inputFileName, String outputFileName) throws InvalidRobotInstructionException{
try{
BufferedReader input = new BufferedReader(new FileReader(inputFileName));
File inner = new File(inputFileName);
Scanner in = new Scanner(input);
PrintWriter wrt;
wrt = new PrintWriter(outputFileName);
if(input.readLine() == null){
System.out.println("Input file not found.");
return;
}
This will read a file in:
Scanner input = new Scanner(new File("input5.txt"));
Don't forget to add throws FileNotFoundException in your main method
edit: I see you added code.
I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.
I am getting the following error messages:
java.io.FileNotFoundException: 10_Random (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at insertionSort.main(insertionSort.java:14)
I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You have to put file extension here
File file = new File("10_Random.txt");
Use following codes to read the file
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
-> This application is printing the file content line by line
here are some working and tested methods;
using Scanner
package io;
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
public static void main(String[] args) throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Here's another way to read entire file (without loop) using Scanner class
package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
using BufferedReader
package io;
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
BufferedReader br=new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine())!=null){
System.out.println(st);
}
}
}
using FileReader
package io;
import java.io.*;
public class ReadingFromFile {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
int i;
while((i=fr.read())!=-1){
System.out.print((char) i);
}
}
}
Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).
Use the Class.getResource method to locate your file in the classpath - don't rely on the current directory:
URL url = insertionSort.class.getResource("10_Random");
File file = new File(url.toURI());
Specify the absolute file path via command-line arguments:
File file = new File(args[0]);
In Eclipse:
Choose "Run configurations"
Go to the "Arguments" tab
Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section
No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.
for (int i =0 ; sc.HasNextLine();i++)
{
array[i] = sc.NextInt();
}
Something to this effect will keep setting values of the array to the next integer read.
Than another for loop can display the numbers in the array.
for (int x=0;x< array.length ; x++)
{
System.out.println("array[x]");
}
You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.
private void loadData() {
Scanner scanner = null;
try {
scanner = new Scanner(new File(getFileName()));
while (scanner.hasNextLine()) {
Scanner lijnScanner = new Scanner(scanner.nextLine());
lijnScanner.useDelimiter(";");
String stadVan = lijnScanner.next();
String stadNaar = lijnScanner.next();
double km = Double.parseDouble(lijnScanner.next());
this.voegToe(new TweeSteden(stadVan, stadNaar), km);
}
} catch (FileNotFoundException e) {
throw new DbException(e.getMessage(), e);
} finally {
if(scanner != null){
scanner.close();
}
}
}
File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file.
Please log the file.getAbsolutePath() to verify that file is correct.
You should use either
File file = new File("bin/10_Random.txt");
Or
File file = new File("src/10_Random.txt");
Relative to the project folder in Eclipse.
The file you read in must have exactly the file name you specify: "10_random" not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.
Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.
At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.
you must use a file name by it's extension in File object constructor, as an example:
File myFile = new File("test.txt");
but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:
Scanner sc = new Scanner(Paths.get("test.txt"));
in this way you must import java.nio.file.Paths as well.