Try/Catch blocks in Java - java

for the program that I have been assigned, we have to read from a text file, create an ArrayList of objects called NameInformation that contains the information from the file, and then prompt the user for a name and gender (Gender is one of the variables in the NameInformation class) and the computer will tell how many boys or girls had the given name.
Can files be accessed and used outside of a try catch block? I want to try something like this:
try {
FileReader inFile = new FileReader (FILE_NAME);
} catch (FileNotFoundException e) {
System.out.println ("The file " + FILE_NAME + " does not exist");
System.exit(-1);
}
Scanner file = new Scanner (infile);
ArrayList<NameInformation> nameList = new ArrayList<NameInformation>();
I tried the above code and kept getting an error message. The only way I could get it to work somewhat was to make the try block massive. Is that the only way to do it? I feel like having a massive try block is incorrect.
I want to add elements to the ArrayList too, but can't seem to get it right.
while (file.hasNextLine()) {
NameInformation babyName = new NameInformation(file.nextLine());
nameList.add(babyName);
}
But this doesn't quite do what I want it to.

You can do it like this and give only error throwing code into try catch block, you are never passing catch block anyway because system exits there, otherwise you should check that file isn't null afterwards:
FileReader inFile = null;
try {
inFile = new FileReader (FILE_NAME);
} catch (FileNotFoundException e) {
System.out.println ("The file " + FILE_NAME + " does not exist");
System.exit(-1);
}
Scanner file = new Scanner (infile);
ArrayList<NameInformation> nameList = new ArrayList<NameInformation>();

Initializing the file should be in Try Catch Block. But you should declare it outside the block to access it outside. Example:
FileReader inFile = null;
try {
inFile = new FileReader (FILE_NAME);
} catch (FileNotFoundException e) {
System.out.println ("The file " + FILE_NAME + " does not exist");
System.exit(-1);
}
Scanner file = new Scanner (infile);
ArrayList<NameInformation> nameList = new ArrayList<NameInformation>();

Related

Where to put any loop type in order to optimize my program that reads and writes content from one file to another?

I am trying to write a program that takes content from one file and outputs it to another. I feel the code I wrote is really inefficient and can be improved with a loop somewhere, either when declaring variables or writing to the output file. Adding another loop is the only real concern I have. I know their are better ways to copy content from one file to another, but the way I chose works best for my understanding as being someone new to java.
public void readFile() {
//File being read
File file = new File("input.in");
try
{
Scanner scnr = new Scanner(file);
while(scnr.hasNext())
{
//Initializing/Declaring variable for each word on file input.in
String contributions = scnr.next();
String max = scnr.next();
String min = scnr.next();
String average = scnr.next();
String total = scnr.next();
try {
//output on file results.out
File outputfile = new File("results.out");
BufferedWriter bw = new BufferedWriter(new FileWriter(outputfile));
//write each line
bw.write(contributions);
bw.newLine();
bw.write(max);
bw.newLine();
bw.write(min);
bw.newLine();
bw.write(average);
bw.newLine();
bw.write(total);
bw.close();
}
catch (IOException e) { // TODOAuto-generated
e.printStackTrace();
}
}
}
catch (FileNotFoundException e)
{ // TODO Auto-generated
e.printStackTrace();
}
}

Why am I getting an error about a Windows file path in Java?

I am getting a "
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at parker.MovieLibrary.<init>(MovieLibrary.java:22)
at parker.SelectorUserInput.main(SelectorUserInput.java:10)
" error when trying to open a file.
Below is the code of the MovieLibrary constructor that is giving me trouble:
public MovieLibrary() {
String FILENAME = "\\Users\\FirstName LastName\\Desktop\\JavaIndividualAssignment\\FinalMovieList1.txt";
Scanner input = new Scanner(FILENAME);
File file = new File(input.nextLine());
String[] split;
try {
File file1 = new File(input.nextLine());
input = new Scanner(file1);
while (input.hasNextLine()) {
String line = input.nextLine();
//code to add movies to an ArrayList
}
//input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
finally{
if (input != null){
input.close();
}
}
}
}
I tired all of the suggestions listed here: Java File Path Windows/Linux
, but none of them worked.I got the same error each time.
I replaced the backslashes with single forward slashes, tried using the Path object, nothing changed the error.
Is this an issue with my file path? I used the same file-opening code on a different computer and it found the file just fine.
Below is the
You are constructing a Scanner object of the filename string (\Users etc). Pretty sure you want to create a File object of the string and a Scanner object of that File object.
String FILENAME = "C:\\Users\\FirstName LastName\\Desktop\\JavaIndividualAssignment\\FinalMovieList1.txt";
Scanner input=null;
File file = new File(FILENAME);
String[] split;
try {
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
//code to add movies to an ArrayList
}
//input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
finally{
if (input != null){
input.close();
}
}
Try This

How to copy a text file, and print out the original and copied file in Java

I'm doing a program that needs to take a text file (test.txt) and make a copy of it and print it out. So far I am only able to print out the original file. I have searched for a way of doing this but there doesn't seem to be any help that I can understand, I am very new to java. I am at least looking for guidance, not just the full answer.
my code so far...
import java.io.*;
public class Copy{
public static void main(String [] args){
try{
FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
File a = new File("test.txt");
FileReader fr = new FileReader(a);
File b = new File("Copied.txt");
FileWriter fw = new FileWriter(b);
while(true){
String line = br.readLine();
if(line != null){
System.out.println(line);
} else{
br.close();
break;
}
}
} catch(FileNotFoundException e){
System.out.println("Error: " + e.getMessage());
} catch(IOException e){
System.out.println("Error: " + e.getMessage());
}
}
}
Again any bit of help will be greatly appreciated since I am trying to learn this. Thank you
Normally, I'd recommend using Files.copy just for it's simplicty, but since you need to "print" the content at the same time, we can make use of your code.
First, however, as a general rule of thumb, if you open it, you should close it. This makes sure that you're not leaving resources open which might affect other parts of your code.
See The try-with-resources Statement for more details.
Next, once you've read a line of text from the source file, you actually need to write it to the destination file, for example...
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("Copied.txt"))) {
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
bw.write(text);
bw.newLine();
}
}
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
You can use Files.copy() if you are using Java 1.7 or higher
File src = "your File";
File dest = "your copy target"
Files.copy(src.toPath(),dest.toPath());
Link to Javadoc
Change your FileWriter into a PrintStream:
PrintStream fw = new PrintStream(b);
Then you should be able to write to that file using:
fw.println(line);

Why is my text file not overwriting after each execution?

My program reads in a text file, in.txt. That text file can have an arbitrary amount of lines.
My problem is that when I try to write to the output (out.txt) file, it appends it instead of overwriting.
The output file should have the same number as the input file.
try {
inFile = new Scanner(new File("in.txt"));
while (inFile.hasNext()) {
// Methods and stuff that doesn't matter...
// Problem starts here
try{
outFile = new PrintWriter((new FileWriter("out.txt", true)));
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
finally {
outFile.flush();
outFile.close();
}
}
}
catch (FileNotFoundException e) {
System.out.print("Could not find the input file. " + e);
e.printStackTrace();
}
The ArrayToString method returns a string to write.
EDIT:
I forgot to add this detail:
After reading the instructions again, I am not supposed to be creating a text file, just checking if it's there.
See the Javadoc for the FileWriter constructor:
public FileWriter(String fileName,
boolean append)
throws IOException
Constructs a FileWriter object given a file name with a boolean
indicating whether or not to append the data written.
Try setting the append flag to false. Then use the same writer instead of creating a new one each time through the loop (meaning that you should declare the FileWriter above the start of your while loop).
(Btw check out java.util.Arrays.toString, you shouldn't need to write your own code for this.)
The problem is here:
try{
outFile = new PrintWriter((new FileWriter("out.txt", true)));
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
Change the PrintWriter line to:
outFile = new PrintWriter((new FileWriter("out.txt", false)));
Now, it looks like you're opening the file on every loop through your input file. If you are wanting to open this file once, and write to it for each line in the input file, move the open and close outside the while loop like this:
try {
inFile = new Scanner(new File("in.txt"));
// here we open the out file, once
outFile = new PrintWriter((new FileWriter("out.txt", false)));
while (inFile.hasNext()) {
// Methods and stuff that doesn't matter...
// Problem starts here
try{
// this will write a line to the out.txt file containing the intArray as a String
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
}
}
catch (FileNotFoundException e) {
System.out.print("Could not find the input file. " + e);
e.printStackTrace();
}
finally {
inFile.close();
outFile.flush();
outFile.close();
}
change
outFile = new PrintWriter((new FileWriter("out.txt", true)));
to
outFile = new PrintWriter((new FileWriter("out.txt", false)));
and
outFile.println(ArrayToString(intArray));
to
outFile.print(ArrayToString(intArray));

FileNotFoundException catch error when reading from file in Java

I am trying to write a simple program that reads integers in from a text file and then outputs the sum to an output file. The only error I am getting is in my catch block at line 38 "Unresolved compilation problem: file cannot be resolved". Note that "file" is the name of my input file object. If I comment out this exception block, the program runs fine. Any advice would be appreciated!
import java.io.*;
import java.util.Scanner;
public class ReadWriteTextFileExample
{
public static void main(String[] args)
{
int num, sum = 0;
try
{
//Create a File object from input1.txt
File file = new File("input1.txt");
Scanner input = new Scanner(file);
while(input.hasNext())
{
//read one integer from input1.txt
num = input.nextInt();
sum += num;
}
input.close();
//create a text file object which you will write the output to
File output1 = new File("output1.txt");
//check whether the file's name already exists in the current directory
if(output1.exists())
{
System.out.println("File already exists");
System.exit(0);
}
PrintWriter pw = new PrintWriter(output1);
pw.println("The sum is " + sum);
pw.close();
}
catch(FileNotFoundException exception)
{
System.out.println("The file " + file.getPath() + " was not found.");
}
catch(IOException exception)
{
System.out.println(exception);
}
}//end main method
}//end ReadWriteTextFileExample
The file variable is declared within the try block. It's out of scope in the catch block. (Although it couldn't happen in this case, imagine if the exception were thrown before execution had even reached the variable declaration. Basically, you can't access a variable in a catch block which is declared in the corresponding try block.)
You should declare it before the try block instead:
File file = new File("input1.txt");
try
{
...
}
catch(FileNotFoundException exception)
{
System.out.println("The file " + file.getPath() + " was not found.");
}
catch(IOException exception)
{
System.out.println(exception);
}
Scope in Java is based on blocks. Any variable you declare inside a block is only in scope until the end of that same block.
try
{ // start try block
File file = ...;
} // end try block
catch (...)
{ // start catch block
// file is out of scope!
} // end catch block
However, if you declare file before your try block, it will remain in scope:
File file = ...;
try
{ // start try block
} // end try block
catch (...)
{ // start catch block
// file is in scope!
} // end catch block

Categories