Buffered Reader Throwing Exception - java

I want to print hello for "t" number of times. So, i have written this code snippet.
import java.util.*;
import java.io.*;
class Buff
{
public static void main(String args[])
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int t = Integer.parseInt(br.readLine());
while(t-->0)
bw.write("hello");
}
}
It outputs an exception
Buff.java:11: error: unreported exception IOException; must be caught or declared to be thrown
String t = br.readLine();
^
Buff.java:14: error: unreported exception IOException; must be caught or declared to be thrown
bw.write("hello");
Please Help !!!
PS : It doesn't help even if i put throws IOException

You have to catch possible exceptions (in this case IOException).
The basic syntax looks like this:
try {
//Your code here
}
catch(IOException e) {
//What do you want to do when something went wrong?
}
In your case, the following code will work:
import java.util.*;
import java.io.*;
class Buff
{
public static void main(String args[])
{
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int t = Integer.parseInt(br.readLine());
//Closing Readers and Writers when not needed anymore is good-practice
br.close();
//"-->" wasn't working for me in this case
while(t > 0) {
bw.write("hello\n");
t--;
}
bw.flush();
bw.close();
}
//Catching possible exceptions
catch(IOException e) {
e.printStackTrace();
}
}
}

Related

Read file name from user input on linux terminal - JAVA

I want to make a little script in JAVA to receive a file name in the linux terminal and read that file.
This is what i'm trying:
import java.util.Scanner;
import java.io.*;
class ItauScript {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Filename: ");
String fileName = reader.next();
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.println(bufferedReader.readLine());
}
}
But the code doesn't compile. I get this error message:
hello.java:10: error: unreported exception FileNotFoundException; must
be caught or declared to be thrown
FileReader fileReader = new FileReader(fileName);
^ hello.java:13: error: unreported exception IOException; must be caught or declared to be thrown
System.out.println(bufferedReader.readLine());
I can open the file if i put it on hardcode on a string.
But i need to receive it as an input from the terminal.
What am i missing?
Try:
import java.util.Scanner;
import java.io.*;
class ItauScript {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Filename: ");
String fileName = reader.next();
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.println(bufferedReader.readLine());
} catch (IOException e) {
// handle exception (if any) here
}
}
}
And as others suggested, it's very helpful to read what the IDE/Compiler tells you in case of errors ...
Hope that helps
FileNotFoundException is a checked Exception (as is the parent class IOException thrown by readLine), modify main to re-throw1 it like
public static void main(String[] args) throws IOException {
or surround it with a try-catch (with resources) like
try (FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
System.out.println(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
1But you should still close the bufferedReader in a finally.
You need to handle the possible exception. You can specify that the enclosing method main throws the exception, but it would be better to handle it yourself.
import java.util.Scanner;
import java.io.*;
class ItauScript {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
try
{
System.out.println("Filename: ");
String fileName = reader.next();
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.println(bufferedReader.readLine());
}
catch(IOException e)
{
e.printStackTrace();
//TODO handle error
return;
}
}
}

Using exceptions in Java with user I/O

I am trying to do the following: I am making a program in Java which let me create and read text files. So far I have been able to do this, but the hard(?) part is this: I have to be able to get an error when anything else but A, B or C is inside the text file.
So far I got:
package textfile;
import java.io.*;
import static java.lang.System.*;
class OutWrite {
public static void main(String[] args) {
try{
FileWriter fw = new FileWriter("FAS.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println("A");
pw.println("B");
pw.println("C");
pw.close();
} catch (IOException e){
out.println("ERROR!");
}
}
}
And
package textfile;
import java.io.*;
import static java.lang.System.*;
class InRead {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("FSA.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null){
out.println(str);
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
}
}
Can anyone steer me in the right direction, please?
Just throw Exception when a new Character is found other than A,B,C .
use,
class InRead {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("FSA.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
if (str.equals("A") || str.equals("B") || str.equals("c")) //compare
out.println(str);
else
throw new Exception(); //throw exception
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
catch (Exception e) {//catch it here and print the req message
System.out.println("New Character Found");
}
}
}

Getting Illegal start of type on try block

So Im trying to get a basic reader going so that I can work with files for an authentication process later.
The problem I am having is that I get an error on my BufferedReader line that causes my try function to throw an illegal start exception and it wont run. Eclipse is showing me an error on the semicolon at the end of the br declaration and says I should be putting a { but I can't see why that would be neccessary.
BufferedReader br = new BufferedReader(new FileReader("Assign4.txt"));
I have tried to put that there but it breaks the entire try section.
package main;
import java.io.*;
public class file_interface
{
BufferedWriter wr = new BufferedWriter(new FileWriter("target.txt"));
BufferedReader br = new BufferedReader(new FileReader("Assign4.txt"));
try
{
int count = 1;
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(count++);
sb.append(line);
sb.append("\n");
wr.write(line);
line = br.readLine();
}
}
catch (IOException e)
{
System.err.println("Error: " + e);
}
finally
{
br.close();
wr.close();
}
}
}
Any Java sentence must be inside a method. This code is not.
The fact that BufferedWriter wr = new BufferedWriter(new FileWriter("target.txt")); works is because is declared as a default field (no scope mark was given) in your file_interface class and is being initialized. It is similar to do:
public class file_interface {
BufferedWriter wr;
public file_interface() {
wr = new BufferedWriter(new FileWriter("target.txt"));
}
}
Just create a method to hold your logic:
public class file_interface {
public void foo() {
//your code goes here...
//now this is not a field but a variable in the method
BufferedWriter wr = new BufferedWriter(new FileWriter("target.txt"));
BufferedReader br = new BufferedReader(new FileReader("Assign4.txt"));
//rest of your code...
try {
//...
} catch (...) {
//...
}
//...
}
}
Then just call your method in your client class. For example, a class with the main method:
public class AMainClass {
public static void main(String[] args) {
file_interface fi = new file_interface();
fi.foo();
}
}
Another example, a class with another method:
public class SomeClientClass {
public void bar() {
file_interface fi = new file_interface();
fi.foo();
}
}
Note: You should also follow the Java Naming Conventions, so you should rename file_interface by FileInterface or even MyFileUtil since interface word sounds more to declare an, uhm, interface.

Error in File I/O

I just started doing file I/O andim using an example from Murach's Se 6.
Here is my code. Am i missing something. I know the code further on has more but as this is an example this should work right?
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
//Answer
by adding a throws exception to the end of where i initialised the main this code works. Even the txt file products.txt is in the class folder as expected.
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args) throws Exception
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
The problem is that a number of the calls to the java.io package throw exceptions.
easy fix: add the following to your method signature
public static void main(String[] args) throws IOException
almost as easy fix: add try/catch/finally blocks.
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = null;
try {
out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
}
catch(IOException ex) {
// todo exception handling
System.out.println("ERROR! " + ex);
}
finally {
out.close();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
}
catch (IOException ex) {
// todo more exception handling
System.out.println("ERROR! " + ex);
}
finally {
in.close();
}
}
edit: you know you are trying to call out.close() twice? The second should be a call to in.close()

This program neither reads nor writes to a file

CODE
import java.io.*;
class tester {
public static void main(String args[]) {
try {
FileReader reader = new FileReader(new File("d:\\UnderTest\\check123.txt"));
FileWriter writer = new FileWriter(new File("d:\\UnderTest\\check123.txt"));
BufferedReader br = new BufferedReader(reader);
String s;
while( (s=br.readLine()) != null ) {
System.out.println(s);
}
writer.write("Shadow Shadow");
} catch(Exception exc) {
System.out.println(exc);
}
}
}
This code writes nothing and reads nothing when i run it. Where is the bug in this program ?
Are you sure that when you read for first time then content is there in the text file ?
You need to close Reader and Writer in finally block (missing currently in your code) of your try-catch block. closing the stream flushes out content automatically.
Make sure you close the reader and the writer. After using the writer you will need to flush the contents or close the writer (which does the same thing). I tested this and it works.
import java.io.*;
class tester {
public static void main(String args[]) {
try {
FileReader reader = new FileReader(new File("c:\\check123.txt"));
FileWriter writer = new FileWriter(new File("c:\\check123.txt"));
BufferedReader br = new BufferedReader(reader);
writer.write("Shadow Shadow");
writer.close();
String s;
while( (s=br.readLine()) != null ) {
System.out.println(s);
}
reader.close();
} catch(Exception exc) {
System.out.println(exc);
}
}
}

Categories

Resources