read from txt and add to treeset - java

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.

Related

JUnit force BufferedReader to throw IOException

I have following method
public static String readPostParams(Request request, String param) {
BufferedReader br = new BufferedReader(new InputStreamReader(request.getBodyAsStream()));
String line;
try {
while ((line = br.readLine()) != null) {
if (line.contains(param)) {
//System.out.println("---> " + param + " :" + getValue(line));
return getValue(line);
}
}
} catch (IOException ex) {
// Ignore
}
return "";
}
I want a JUnit Unit test to force BufferedReader to throw IOException so I can cover that part also.
You should get an IOException if the file is "in use" So you can try this:
(I have never tested this)
In you test use
final RandomAccessFile lockFile = new RandomAccessFile(fileName, "rw");
lockFile.getChannel().lock();
Then call your method from above and unlock the file once you are done.
If you want to test this method for IOException, you should propagate the exception to the calling method by removing the try catch block and adding the throws clause to your method:
public static String readPostParams(Request request, String param) throws IOException;
There is an attribute called as 'expected' for the #Test annotation which you can use to check for exceptions. Your test case which checks for IOexception from your method will look somewhat like this:
#Test(expected=IOException.class)
public void shouldReadPostParamsThrowIOExceptionIfInvalidRead(){
}

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.

Can I miss the catch clause to throw exception to its caller?

What kind of problem may occur for this code?
I think even exception occurs, this code can throw the exception to its caller.
So it does NOT generate any trouble.
How can I improve it?
public static void cat(File named) {
RandomAccessFile input = null;
String line = null;
try {
input = new RandomAccessFile(named, “r”);
while ((line = input.readLine()) != null {
System.out.println(line);
}
return;
} finally {
if (input != null) {
input.close();
}
}
}
The code has to throw the IOException - try editing your code with eclipse and you would also get a suggestion to throw the Exception.
Also Java 1.7 has the new concept of "try-with-resources" - see the try statement below.
The resource used in try (...) is closed automatically.
public static void cat(File named) throws IOException
{
try (RandomAccessFile input = new RandomAccessFile(named, "r"))
{
String line = null;
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
}
}
What kind of problem may occur for this code?
public RandomAccessFile throws FileNotFoundException.
public final String readLine() throws IOException.
public void close() throws IOException.
Since public class FileNotFoundException
extends IOException
You can change your method to:
public static void cat(File named) throws IOException
And now you don't need a try-catch blocks.
And the caller should catch the exception thrown by the method.
But why don't you want to catch the exceptions?
add the throws declaration in your method , and then caller of this method should have try catch block for this exception .
public static void cat(File named) throws IOException {
RandomAccessFile input = null;
String line = null;
try {
input = new RandomAccessFile(named, "r");
while ((line = input.readLine()) != null ){
System.out.println(line);
}
return;
} finally {
if (input != null) {
input.close();
}
}
}
//caller
try{
Class.cat(new File("abc.txt"));
}catch(IOException e)
{
//
}

How to correctly handle this IOException?

public void tokenize(){
// attempt creating a reader for the input
reader = this.newReader();
while((line = reader.readLine())!=null){
tokenizer = new StringTokenizer(line);
while(tokenizer.hasMoreTokens()){
toke = (tokenizer.nextToken().trim());
this.tokenType(toke);
//System.out.println(this.tokenType(toke));
}
}
}
private BufferedReader newReader(){
try {//attempt to read the file
reader = new BufferedReader(new FileReader("Input.txt"));
}
catch(FileNotFoundException e){
System.out.println("File not found");
}
catch(IOException e){
System.out.println("I/O Exception");
}
return reader;
}
I thought I had handled it within newReader() but it appears to be unreachable. Eclipse recommends a throws but I don't understand what that's doing, or if it's even solving the problem?
Appreciate the help!
If you don't know how to handle an IOException in this method, then it means that it's not the responsibility of the method to handle it, and it should thus be thrown by the method.
The reader should be closed in this method, though, since this method opens it:
public void tokenize() throws IOException {
BufferedReader reader = null;
try {
// attempt creating a reader for the input
reader = this.newReader();
...
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException e) {
// nothing to do anymore: ignoring
}
}
}
}
Also, note that unless your class is itself a kind of Reader wrapping another reader, and thus has a close method, the reader shouldn't be an instance field. It should be a local variable as shown in my example.

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