Reading Character in Java - java

I work in BlueJ in Windows. I tried to read a character in Java using the following method:
import java.util.Scanner;
import java.io.*;
public class Test{
public static void main(String args[]) {
InputStreamReader instream = new InputStreamReader (System.in);
BufferedReader stdin = new BufferedReader(instream);
char c = (char) stdin.read();
}
}
When I compiled it, the compiler gave an error:
Unreported exception java.io.IOException; must be caught or declared
I did not understand the problem. Can anyone suggest me a way to do it properly.

The line stdin.read() could throw an IOException which is what the error message is telling you. You need to handle this by either declaring that your main method will throw it:
public static void main(String args[]) throws IOException {
// ...
}
or by handling the IOException inside main by using a try/catch like this:
public static void main(String args[]) {
try {
InputStreamReader instream = new InputStreamReader (System.in);
BufferedReader stdin = new BufferedReader(instream);
char c = (char) stdin.read();
} catch (IOException ex) {
// handle error in some way
ex.printStackTrace();
}
}

Use try catch block to handle IOException in your code. you can do this.
import java.util.Scanner;
import java.io.*;
public class Test {
public static void main(String args[]) {
try {
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(instream);
char c = (char) stdin.read();
} catch (IOException ex) {
System.out.println("Error : " + ex.getMessage());
}
}
}

Catch the exception.
public static void main(String args[]) {
try{
InputStreamReader instream = new InputStreamReader (System.in);
BufferedReader stdin = new BufferedReader(instream);
char c = (char) stdin.read();
}catch(IOException ioe){
ioe.printStackTrace();
// write your handling
}catch(Exception err){
err.printStackTrace();
}
}
// You can catch relevant multiple exceptions using catch block. If you are not sure of specific exception, catch generic Exception. All sub classes of Exception should be handled first and generic Exception should be caught in the last.

Related

Want a code to be written without throwing exception

I have the below piece of code.
import java.io.*;
public class FileTest {
public static void main(String[] args) throws IOException {
WriteLinesToFile("miss.txt","This is a special file");
}
public static void WriteLinesToFile(String outputFileName, String lineConverted) throws IOException {
File f = new File(outputFileName);
if (f.createNewFile()) {
System.out.println("File is created!");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
} else {
System.out.println("File already exists.");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
}
}
}
I need the same logic, without throwing exception. Could someone tell me how to do this?
You could handle your exception with a try{} catch(IOException e){}
But it's important to handle the exception, because otherwise your program will do something, but not what you want.
import java.io.*;
public class FileTest {
public static void main(String[] args)
{
writeLinesToFile("miss.txt", "This is a special file");
}
public static void writeLinesToFile(String outputFileName, String lineConverted){
File f = new File(outputFileName);
try {
if (f.createNewFile()) {
System.out.println("File is created!");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
} else {
System.out.println("File already exists.");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
}
}
catch(IOException e){
//Handle your error
}
}}
But you can't cut out the exceptions at all, because handling files in java throws always exceptions (For example if the file could not be found).

Why fileWriter is not saving the content to my file?

It's not showing any error but the content should be saved to my file, which is not saving...
import java.util.Scanner;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FileReadLine {
public static void main(String[] args) {
try {
String str;
Scanner sc=new Scanner(System.in);
do {
System.out.println("Enter your lines");
str=sc.nextLine();
FileWriter fw = new FileWriter("C:/test/abcd.txt");
if(!str.equals("stop"))
fw.write(str);
fw.write("\n");
fw.close();
} while(!str.equals("stop"));
} catch (Exception ex) {
System.out.println(ex);
}
}
}
please correct my code if i am wrong
You are trying to create a new file inside the loop. So it gets overridden. Change the program to create the file once(before loop) and use it inside the loop to write it.
Also do not close the file as soon as you have written it. Use it once you encounter "stop". Close() should be used when you are done with writing into the file.
Try using flush() before close() to send all data in the buffer to the the file.
You must close you FileWriter (fw) out of while loop.
Try below code
public static void main(String[] args) throws IOException {
FileWriter fw = null;
try {
fw = new FileWriter("C:/Users/MYPC/Desktop/abcd.txt");
String str;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter your lines");
str = sc.nextLine();
if (!str.equals("stop")){
fw.write(str);
}
fw.write("\n");
} while (!str.equals("stop"));
} catch (Exception ex) {
System.out.println(ex);
// Logger.getLogger(FileReadLine.class.getName()).log(Level.SEVERE,
// null, ex);
}finally{
if(fw != null){
fw.close();
}
}
}
You were closing the writer in every iteration since you are not using braces in the if condition...
Try this solution, is working
try {
String str;
Scanner sc=new Scanner(System.in);
File fw = new File("C:/Users/MYPC/Desktop/abcd.txt");
FileOutputStream fos = new FileOutputStream(fw);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
do {
System.out.println("Enter your lines");
str=sc.nextLine();
if(!str.equals("stop")) {
bw.write(str);
bw.newLine();
} else {
bw.close();
}
} while(!str.equals("stop"));
} catch (Exception ex) {
System.out.println(ex);
}

Not being able to write output to text file in JAVA

I'm trying to output the squares of the numbers 1-10 to a file named Squares but i'm having an error with the OutputStream.print(i+"\t"+(i*i)); part. The print is being underlined and i can't understand why. Please help me.
Here's the codes:
import java.util.*;
import java.io.*;
public class Number1 {
public static void main(String[] args) throws FileNotFoundException {
FileOutputStream fos = new FileOutputStream("Squares.txt");
PrintWriter square;
try{
square = new PrintWriter(fos);
} catch (Exception e) {
System.out.print("Could not create/open file");
System.exit(0);
}
for(int i=1; i<=10; i++)
{
OutputStream.print(i+"\t"+(i*i));
}
}
}
Complete solution:
import java.io.*;
public class Number1 {
public static void main(String[] args) throws FileNotFoundException {
FileOutputStream fos = new FileOutputStream("Squares.txt");
PrintWriter square = null;
try{
square = new PrintWriter(fos);
}
catch (Exception e)
{
System.out.print("Could not create/open file");
System.exit(0);
}
for(int i=1; i<=10; i++)
{
square.print(i+"\t"+(i*i));
}
square.close();
}
}
OutputStream has no print method ,and even if it had one, it would probably not be a static method.
Use your PrintWriter instance to write to the file.
public static void main(String[] args) throws FileNotFoundException
{
FileOutputStream fos = new FileOutputStream("Squares.txt");
try{
PrintWriter square = new PrintWriter(fos);
for(int i=1; i<=10; i++) {
square.print(i+"\t"+(i*i));
}
square.close ();
}
catch (Exception e) {
System.out.print("Could not create/open file");
System.exit(0);
}
}
You have to call square.print(i+"\t"+(i*i)); instead of OutputStream.print(i+"\t"+(i*i));
You are calling print on the class OutputStream rather than on an instance of a class that has that function. What you probably want to do is
square.print(i+"\t"+(i*i));
To quickly make your code to work,
move the for loop into the try{} statement, and also instead of wrongly calling the OutputStream.print, use the command: square.print
You should use fos.write((i+"\t"+(i*i)).getBytes());

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