Equivalent of try-with-resources but throw the exception - java

I have a function read:
public static ArrayList<String> read(Path path) throws FileNotFoundException {
ArrayList<String> lines = new ArrayList<String>();
File fileToRead = path.toFile();
Scanner fileReader = new Scanner(fileToRead);
while (fileReader.hasNext()) {
lines.add(fileReader.nextLine());
}
fileReader.close();
return lines;
}
I want it to pass on a FileNotFoundException if it encounters one, but I'm not sure if encountering this exception while creating the scanner will result in an unclosed scanner.
I'd like to implement a similar behavior that the try-with-resources block provides as shown below, but without catching and re-throwing the error (unless this is the intended solution).
public static ArrayList<String> read(Path path) throws FileNotFoundException {
ArrayList<String> lines = new ArrayList<String>();
File fileToRead = path.toFile();
try (
Scanner fileReader = new Scanner(fileToRead);
) {
while (fileReader.hasNext()) {
lines.add(fileReader.nextLine());
}
}
catch (FileNotFoundException e) {
throw e;
}
return lines;
}

Related

Access variable in try block

I want to remove the throws FileNotFoundException from the method head and put it into it.
public static String[] read(String file) throws FileNotFoundException {
But then I can't access in (the scanner) anymore! How to handle that?
public static String[] read(String file) {
try {
Scanner in = new Scanner(new FileReader(file));
}
catch (Exception e) {
}
// ...
in.close();
// ...
}
Just use try-with-resources so you dont have to worry about closing the scanner object.
try (Scanner in = new Scanner(new FileReader(file))) {
//Your code
}
catch (Exception e) {
}
you can use try with ressource, that permit to close automaticaly your in.
like that
Scanner in ;
try ( in = new Scanner(new FileReader(file))) {
}
catch (Exception e) {
}
The variable in is out of scope outside the try block. You can either do this:
public static String[] read(String file) {
Scanner in = null;
try {
in = new Scanner(new FileReader(file));
}
catch (Exception e) {
}
finally() {
in.close();
}
// ...
}
Or better yet, try with resources
public static String[] read(String file) {
try (Scanner in = new Scanner(new FileReader(file))){
String line = in.nextLine();
// whatever comes next
}
catch (Exception e) {
}
// right here, the scanner object will be already closed
return ...;
}
The in variable is locally scoped to the try block. You can either declared the variable before the try block, or close in within the try block. There's not much use in closing it if it never successfully opened.

Java static printstream error [duplicate]

This question already has answers here:
Java: startingPath as "public static final" exception
(5 answers)
Closed 5 years ago.
Unreported exception java.io.FileNotFoundException; must be
caught or declared to be thrown
I'm writing a basic program to generate a a script. I'm using two methods to write to the file, so, I thought I'd user a static level file and printstream.`
static String fileName = "R1";
static File inputFile = new File(fileName+".txt");
static PrintStream write = new PrintStream(fileName+"_script.txt");
`
It won't run, it asks me to catch or throw. Do I have to add a try-catch clause in the class level and is that even possible?
PrintStream constructor is throwing an exception that you need to catch, but you are not able to handle that if you just do;
static PrintStream write = new PrintStream(fileName + "_script.txt");
so your options are:
try defining a static block
static String fileName = "R1";
static File inputFile = new File(fileName + ".txt");
static {
try {
PrintStream write = new PrintStream(fileName + "_script.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
or even better define a static method to initialize those objects:
static String fileName;
static File inputFile;
static PrintStream write;
public static void init() throws FileNotFoundException {
fileName = "R1";
inputFile = new File(fileName + ".txt");
write = new PrintStream(fileName + "_script.txt");
}
You can't initialize PrintStream like this, because it should throw an exception so you have to catch this exception, how? you can create a method which can throw this exception for example :
static String fileName;
static File inputFile;
static PrintStream write;
public static void init() throws FileNotFoundException {
//------------------^^-------^^
fileName = "R1";
inputFile = new File(fileName + ".txt");
write = new PrintStream(fileName + "_script.txt");
}
Or even you can catch your exception with :
public static void init() {
fileName = "R1";
inputFile = new File(fileName + ".txt");
try {
write = new PrintStream(fileName + "_script.txt");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}

read from txt and add to treeset

I need to read a txt file and store my data to a treeSet.
public class UrbanPopulationStatistics {
private Set<UrbanPopulation> popSet;
private File file;
private BufferedReader br;
public UrbanPopulationStatistics(String fileName) throws IOException {
this.popSet = new TreeSet<>();
readFile("population.txt");
}
private void readFile(String fileName) throws IOException {
try {
br = new BufferedReader(new FileReader(fileName));
String line;
while ((line=br.readLine()) != null) {
String[] array = line.split("/");
popSet.add(new UrbanPopulation(array[0], Integer.parseInt(array[1]), Integer.parseInt(array[4])));
}
} catch (IOException e) {
e.printStackTrace();
}
br.close();
}
#Override
public String toString() {
String s = popSet.toString().replaceAll(", ", "");
return "UrbanPopulationStatistics:\n" + s.substring(1, s.length() - 1) + "\n";
}
public static void main(String[] args) throws IOException {
UrbanPopulationStatistics stats = new UrbanPopulationStatistics("population.txt");
System.out.println(stats);
}
}
I have tried to turn what the buffered reader reads into an array and then add it into my treeSet, but I get the error: Exception in thread "main" java.lang.UnsupportedOperationException: Not supported yet.
You have an extra period after parseInt at Integer.parseInt.(array[4])));.
Be careful when writing code. Syntax errors don't show up "nicely", i.e. the error message is not very helpful in most cases. It does show you the approximate location of the error though.
The problem with your code is you are not storing what you read from the buffer (and hence reading twice from the buffer). You need to assign what you read in a variable to check for null as below:
private void readFile(String fileName) throws IOException {
try {
br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
String[] array = line.split("/");
popSet.add(new UrbanPopulation(array[0], Integer.parseInt(array[1]), Integer.parseInt(array[4])));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
br.close();
}
}
Also I would close the BufferedReader in the finally block to avoid resource leaks.
I tried to reproduce the error using your code, but it doesn't happened. Your code is ok.
UnsupportedOperationException are exceptions that can happen when you try to add an element in a collection.
But TreeSet implements the add method.

Resolving IOException, FileNotFoundException when using FileReader

I've not been able to resolve the following exception in the code below. What is the problem with the way I use BufferedReader? I'm using BufferedReader inside the main method
OUTPUT :-
ParseFileName.java:56: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
// ParseFileName is used to get the file name from a file path
// For eg: get - crc.v from "$ROOT/rtl/..path/crc.v"
import java.util.regex.Pattern;
import java.io.*;
public class ParseFileName {
//Split along /'s , and collect the last term.
public String getName (String longName) {
String splitAt = "/";
Pattern pattern1 = Pattern.compile(splitAt);
String[] parts = pattern1.split(longName);
System.out.println("\nparts.length = " + parts.length);
//Return the last element in the array of strings
return parts[parts.length -1];
}
public static void main(String[] args) {
ParseFileName superParse = new ParseFileName();
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
String line;
while ((line = buffread.readLine())!= null) {
String fileName = superParse.getName(line);
System.out.println("\n" + line + " => " + fileName);
}
buffread.close();
}
}
UPDATE :
The following works:
public static void main(String[] args) throws FileNotFoundException, IOException {
However try.. catch still has some nagging issues for me:
try {
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex2) {
ex2.printStackTrace();
}
buffread dosent seem to get the file name. I get this error:
javac ParseFileName.java ParseFileName.java:67: cannot resolve symbol
symbol : variable buffread
location: class ParseFileName
while ((line = buffread.readLine())!= null) {
Add throws FileNotFoundException, IOException in the header of your method. It looks like just throwing the IOException will solve your problem, but incorporating both will allow you to tell if there was a problem with the file's existence or if something else went wrong (see catch statements below).
i.e.
public static void main(String[] args) throws FileNotFoundException, IOException {
Alternately, if you'd like to catch a specific exception and do something with it:
try {
BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
// Do something with 'ex'
} catch (IOException ex2) {
// Do something with 'ex2'
}
Update to resolve the updated issue: This is just a simple scope problem which can be solved by declaring the BufferedReader outside of the try statement.
BufferedReader buffread = null;
try {
buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
...
You have to add throws statement into the signature of method main or wrap code in
try {
...
} catch (FileNotFoundException e) {
...
}
Your code can throw FileNotFoundException or IOException which is Checked Exception. You need to surround your code in a try-catch block or add a throws declaration in your main function.
The BufferReader can throw an exception if the file cannot be found or opened correctly.
This error message is telling you that you need to handle this exception. You can wrap the line where you create the BufferReader in a try/catch block. This will handle the case an IOException is thrown and print out the stack trace.
public static void main(String[] args) {
ParseFileName superParse = new ParseFileName();
BufferedReader buffread;
try
{
buffread= new BufferedReader (new FileReader("file.txt"));
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
String line;
while ((line = buffread.readLine())!= null) {
String fileName = superParse.getName(line);
System.out.println("\n" + line + " => " + fileName);
}
buffread.close();
}
Another option is to add "throws IOException" to your method header.
public static void main(String[] args) throws IOException {
//...
}
This tells the compiler and callers of your method that you are choosing to not handle this exception and there is a chance it will be thrown.

Java text file reading program with bufferedreader and FileReader. Compiling But not working

This program is compiling though not working. It just handling the opening file exception. Please help me.Thanks for your time.
import java.io.*;
import java.util.Scanner;
public class ReadingFile {
/**
* #param args
*/
public static void main(String[] args) {
ReadingFile rf = new ReadingFile();
rf.printOnScr();
}
private BufferedReader openFile(String meString){
Scanner sc = new Scanner(System.in);
BufferedReader bf = null;
while (bf == null) {
try {
System.out.println("Enter a file name");
String fileName = sc.nextLine();
FileReader b = new FileReader(fileName);
bf = new BufferedReader(b);
} catch (IOException e) {
System.out.println("The file you are trying to open dose not exist.");
}
}
return bf;
}
private void printOnScr() {
BufferedReader br = openFile("Please enter a file");
try {
while(true){
String line = br.readLine();
if(line == null) break;
System.out.println(line);
}
br.close();
} catch (IOException e) {
System.out.println("The line you are trying to access have problem/s");
}
}
}
Very probably you're not specifying the correct path to the file when you type it. It should either be an absolute path or a relative path based at your current working directory. To see exactly what's happening, though, you'll need to look at the exception that's thrown. Either print it out with
e.printStackTrace()
or wrap it in an unchecked exception:
throw new IllegalStateException(e);
or let IOException be thrown from openFile(), through printOnScr(), and out of main()

Categories