Error in File I/O - java

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()

Related

Buffered Reader Throwing Exception

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();
}
}
}

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;
}
}
}

flush() method of printwriter doesnt work

I am trying to write to a file, which another process can read. I am using the Printwiter to write to a file. But it doesnt write to the file as long as i dont terminate the program. I have eanbles the autflush on, and even explicitly flusing. The code is below -
import java.io.FileWriter;
import java.io.PrintWriter;
public class ReadFile {
public static void main(String[] args) {
try {
// Create a print writer
FileWriter fw = new FileWriter("D:\\SpringProjects\\RescilienceModel\\natural_resource.txt");
//BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(fw, true);
// Experiment with some methods
while(true)
{
pw.println(99);
pw.flush();
}
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
Two issues.
Check that while(true) loop, or it won't end.
close() your handle, or it won't release resources.

How to create a txt file in Java?

I'm just want a program to register a user and then create a txt file to store there the information. I know it has to be with createNewFile method but I do not know how to use it. I'd try this in my code:
import java.util.*;
public class File{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
byte option=0;
do{
System.out.println("\nMENU:\n");
System.out.println("0.-EXIT");
System.out.println("1.-REGISTER USER");
System.out.println("\nPLEASE ENTER YOUR CHOICE:");
option = sc.nextByte();
}while(option!=0);
}//main
}//File
You can use a File object to create a new File an example is:
File createFile = new File("C:\\Users\\youruser\\desktop\\mynewfile.txt");
createFile.createNewFile();
If you want to read and write to the file you could use a PrintWriter or some other writing mechanism:
PrintWriter pw = new PrintWriter(createFile);
pw.write("File Contents");
//when you are done flush and close the pw
pw.flush();
pw.close();
If you need to append to the file you can do this:
PrintWriter pw = new PrintWriter(new FileOutputStream(createFile, true)); //true means append here
pw.append("File Contents");
//when you are done flush and close the pw
pw.flush();
pw.close();
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
// File file = new File("/users/your_user_name/filename.txt");// unix case
File file = new File("c:\\filename.txt"); //windows case
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Source: http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
Ok so once you have the input from the user this is what you would use to write the username and password to a text file
try {
File file = new File("userInfo.txt");
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
//set to true so you can add multiple users(it will append (false will create a new one everytime))
output.write(username + "," + password);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
EDIT***
You can put all this in a method and call it every time you want to add the user
public void addUser(String username, String password){
//my code from above ^^
}

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