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;
}
}
}
Related
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();
}
}
}
This question already has an answer here:
What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?
(1 answer)
Closed 7 years ago.
I am trying to write a test file that will overwrite the file I am working on so I can use it with a much more complex program. I keep getting an error message associated with creating a new PrintWriter.
This is the error message:
unreported exception java.io.FileNotFoundException; must be caught or
declared to be thrown
PrintWriter printWriter = new PrintWriter(file);
This is my code:
import java.io.PrintWriter;
import java.io.File;
public class rewriting_test_file {
public static void main(String[] args) {
File file = new File ("C:/Users/XXXXXXX/Desktop/Java practice/rewriting_test_file.java");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
printWriter.println ("hello");
printWriter.close ();
}
}
As the error says, you need to throw the Exception or catch it in try/catch block. Take a look at Exception handling tutorial
public static void main(String[] args) throws IOException
{
File file = new File ("C:/Users/XXXXXXX/Desktop/Java practice/rewriting_test_file.java");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
printWriter.println ("hello");
printWriter.close ();
}
}
or
public static void main(String[] args)
{
PrintWriter printWriter = null;
try{
File file = new File ("C:/Users/XXXXXXX/Desktop/Java practice/rewriting_test_file.java");
file.getParentFile().mkdirs();
printWriter = new PrintWriter(file);
printWriter.println ("hello");
}
catch(IOException e){
e.printStackTrace();
}
finally{
if(printWriter!=null)
printWriter.close (); //always close the resources in finally block
}
}
}
The error message says it all.
Creating a PrintWriter might throw a FileNotFoundException if the file you give it doesn't exist.
You have to wrap it in a try/catch block:
try{
PrintWriter pw = new PrintWriter(file);
//do more stuff
}catch(FileNotFoundException e){
System.out.println("File doesn't exist. Here's the stack trace:");
e.printStackTrace();
}
Alternatively, declare that your method throws an exception:
public static void main(String[] args) throws IOException { //...
so Im trying to write this class which is going to parse a file and read commands from it.
I want the ctor to just open the stream and do nothing else.
while I parse the file in other class methods.
But I'm getting a nullpointerexception when I try to read the file in the methods I made.
help will be apprecated :D
public class Parser {
private BufferedReader _input;
private String _command;
public Parser(String filename) throws FileNotFoundException {
FileInputStream fstream = new FileInputStream(filename);
BufferedReader _input = new BufferedReader(new InputStreamReader(fstream));
}
public boolean hasMoreCommands() throws IOException {
String line;
if ( (line = _input.readLine()) != null) {
return true;
} else {
_input.close();
return false;
}
}
public void advance() throws IOException {
String line;
do {
line = _input.readLine().trim();
} while (line.equals("") || line.substring(0,2).equals(COMMENT_SIGN));
String[] splittedLine = line.split(COMMENT_SIGN);
_command = splittedLine[0];
_command = _command.replace(" ", "");
}
my main for testing it + the exception trace
public static void main(String[] args) throws IOException {
Parser input = null;
input = new Parser("D:\\test.asm");
System.out.println( input.hasMoreCommands());
}
Exception in thread "main" java.lang.NullPointerException
at nand6.Parser.hasMoreCommands(Parser.java:40)
at nand6.Parser.main(Parser.java:116)
Have a look at this snippet of code
public Parser(String filename) throws FileNotFoundException {
FileInputStream fstream = new FileInputStream(_filename);
BufferedReader _input = new BufferedReader(new InputStreamReader(fstream));
}
Change
BufferedReader _input = new BufferedReader(new InputStreamReader(fstream));
to
_input = new BufferedReader(new InputStreamReader(fstream));
Your mistake : You are creating another local variable of type *BufferedReader _input* hence your class level variable is still null resulting in a NullPointerException
You are basically defining a new BufferedReader object called "_input" inside your constructor. You think that after calling the constructor you instantiate "_input" outside the constructor. But you are not, it refers to null. That's why you are getting NullPointerException. Just remove "BufferedReader" in front of "_input" inside your constructor, in order to refer to correct object.
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()
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);
}
}
}