My data is not getting transferred to the output file , I always get an Exception.
import java.io.*;
import java.util.*;
class TransferData {
public static void main(String[] args) {
String path1="E:\\IO\\Input.txt";
String path2="E:\\IO\\Output.txt";
int data;
System.out.println("Transfering started...");
try {
FileInputStream fis=new FileInputStream(path1);
FileOutputStream fos=new FileOutputStream(path2);
while((data=fis.read())!=-1) {
fos.write(data);
}
}
catch(Exception e) {
System.out.println("exception caught!");
}
System.out.println("Completed...");
}
}
How do I transfer data to output file ?
Tested this code on my local machine it is works without exceptions.
Check is file E:/IO/Input.txt exists.
IS Directory E:/IO is writeable for your user
(If file E:/IO/Output.txt already exists check is it writeable and not opened in another programm)
By code:
It is good practice to close FIS and FOS after programm finished execution.
public class TransferData {
public static void main(String[] args) {
String path1 = "E:\\IO\\Input.txt";
String path2 = "E:\\IO\\Output.txt";
int data;
System.out.println("Transfering started...");
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(path1);
fos = new FileOutputStream(path2);
while ((data = fis.read()) != -1) {
fos.write(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Completed...");
}
}
If you replace System.out.println("exception caught!"); with e.printStackTrace(); then you will get a much more useful error message.
If you then post that error message here, people will be able to help you much more easily.
It could be the case that the program cannot find the file you're trying to read.
I highly suggest to use e.printStackTrace() as the others suggested.
One possible problem might be the filesystem permissions or the file you are trying to read from being not existent.
You might also want to use a "try with resources" to simplify your code.
Your code is missing a close statement for your Streams too.
All together your code would look something like this:
import java.io.*;
import java.util.*;
class TransferData {
public static void main(String[] args) {
String path1="E:\\IO\\Input.txt";
String path2="E:\\IO\\Output.txt";
int data;
System.out.println("Transfering started...");
try (
FileInputStream fis=new FileInputStream(path1);
FileOutputStream fos=new FileOutputStream(path2)
) {
while((data=fis.read())!=-1) {
fos.write(data);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
One last thing, if you post your code on StackOverflow, please do not mix different formatting styles (e.g. { in the same line as an if and sometimes in the next) and try to have the code well formatted from the beginning.
Add e.printStackTrace() to your catch block, and post the data printed in your console here, people will be able to help you better.
The most likely cause of the exception getting thrown is that the system is not able to find the file "E:\\IO\\Input.txt" or "E:\\IO\\Output.txt" make sure that the file's are there and Output.txt is not set to read only.
Related
Hi I am beginner in java please explain the things in simple terms.I am making FileHandling.java file in which I try to read from a file and write to other file but after read and write operation I want to close both files but my main problem is how I will get to know whether there was such file or not .On the basis of whether file exists or not I want to close my files.Here is my java code:
import java.io.*;
public class FileHandling {
public static void main(String args[])
{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
catch(IOException e)
{
System.out.println("Here some IO problem :"+e);
}
finally {
System.out.println("Finally Block executed");
if(in.exists()){in.close();System.out.println("in file closed");}
else{System.out.println("in file doesn't exist to close operation");}
if(out.exists()){out.close();System.out.println("out file closed");}
else{System.out.println("out file doesn't exist to close operation");}
}
}
}
You can check if they are null
finally {
System.out.println("Finally Block executed");
if(in != null ){
in.close();
System.out.println("in file closed");
}
else{
System.out.println("in file doesn't exist to close operation");
}
if(out != null){
out.close();
System.out.println("out file closed");}
else{
System.out.println("out file doesn't exist to close operation");}
}
}
Alternatively you can use try with resources if using Java 7 or above.
try (in = new FileInputStream("input.txt")) {
try (out = new FileOutputStream("output.txt")) {
}
}
This will close the resources automatically once the method completes, without the use of finally block.
I really need help with Java io manipulation of Streams. I don't know why this won't show me the contents of the file. I need to be able to view the text in this binary file "Data.abc" If I can view the contents of this file, i need to create a switch case condition to display it's contents per row / column.
Everytime I run the program, it returns some weird letters and characters like � NAme Address�����
Please help. I'm new to manipulation of streams. Thanks.
package IO_ReadFile;
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
InputStream istream; // creates an Input Stream and named it "istream"
OutputStream ostream; // creates an Output Stream and named it "ostream"
File inputFile = new File("Data.abc"); //passes file as argument
int c;
final int EOF=-1;
ostream = System.out;
try
{
istream = new FileInputStream(inputFile);
try
{
while((c=istream.read()) !=EOF)
ostream.write(c);
}
catch(IOException e)
{
System.out.println("Error: " + e.getMessage());
}
finally
{
try
{
istream.close();
ostream.close();
}
catch(IOException e)
{
System.out.println("File did not close");
}
}
}
catch(FileNotFoundException e)
{
System.exit(1);
}
}
}
I get error that variable fin might not have been initialized in the following program. Please clear me the concept about initialization. :
import java.io.*;
class ShowFile
{
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
try
{
fin=new FileInputStream(args[0]);
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("Array index are out of bound");}
do
{
i=fin.read();
System.out.println((char) i);
} while(i!=-1);
fin.close();
}
}
but in the following code, I don't get such error
import java.io.*;
class ShowFile {
public static void main(String args[])
{
int i;
FileInputStream fin;
// First, confirm that a file name has been specified.
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
// Attempt to open the file.
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Cannot Open File");
return;
}
// At this point, the file is open and can be read.
// The following reads characters until EOF is encountered.
try {
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(IOException e) {
System.out.println("Error Reading File");
}
// Close the file.
try {
fin.close();
} catch(IOException e) {
System.out.println("Error Closing File");
}
}
}
Why so ? Please help me. and sorry for the inconvenience in reading. It's my first post so I don't know that exactly how to post.
Thank you.
You have this try-catch block
try {
fin=new FileInputStream(args[0]);
} catch(...) {
.....
}
where you catch a potential FileNotFoundException then outside of it you you access fin
If an exception occurs in the first block, then fin will be uninitialized and you will end up with an NPE
Move the reading inside the first block.
try {
fin=new FileInputStream(args[0]);
do {
i=fin.read();
System.out.println((char) i);
} while(i!=-1);
} catch(...) {
.....
} finally {
if(fin != null) {
try { fin.close(); } catch(IOException e) {}
}
}
A variable needs to be initialized before it is used.
In your case, for example, this line fin=new FileInputStream(args[0]); might throw an exception (suppose, the file does not exist), you catch the exception, print it out, and then do this i=fin.read();
Here fin might not have been initialized.
In general, it is a good idea to always initialized all variables when you declare them:
int i = 0;
InputStream fin = null;
Next time, please also post the actual error message you need help with. It helps not having to try to "compile" your code mentally to guess what you are talking about.
For variables declared and not initializsed inside a method, there must not be any possible execution path from the declaration to any point of the variable's use. This is checked by the compiler, and it won't let you compule.
Fields in a class are always initiialzed, possibly with zero, so it does not apply to these.
I am trying to enter data into a text file from a java program. The program is executing and showing the output as success but when i open the text file it is still blank.
Here is my code
package com.example.ex2;
import java.io.*;
class Input{
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("abc.txt");
String s="Good MOrning";
byte b[]=s.getBytes();
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){
System.out.println(e);}
}
}
I think i have gone wrong in placing the text file. I have placed it in the default directory.
Your code works fine. Check the correct file.
If you are running from IDE, it will be in the current working directory.
It is always better to your a temp or directory to store files ( certainly not in working dir)
Here is a best practice code. You can tune it further if you wish
public static void main(String args[])
{
FileOutputStream fout = null;
try
{
File f = new File("abc.txt");
if (!f.isFile())
f.createNewFile();
fout = new FileOutputStream(f);
String s = "Good MOrning";
byte b[] = s.getBytes();
fout.write(b);
System.out.println("success... printed at : " + f.getAbsolutePath());
} catch (Exception e)
{
System.out.println(e);
} finally
{
if (null != fout)
try
{
fout.close();
} catch (IOException e)
{
}
}
}
I'm write some text a file then delete it, but the deletion is failed.
The code is very simple:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class TestFile {
public static void main(String[] args) throws IOException {
File file = new File("c:\\abc.txt");
writeFile(file, "hello");
// delete the file
boolean deleted = file.delete();
System.out.println("Deleted? " + deleted);
}
public static void writeFile(File file, String content) throws IOException {
OutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(content.getBytes("UTF-8"));
} catch (IOException e) {
try {
out.close();
} catch (IOException e1) {
// ignored
}
}
}
}
The output is:
Deleted? false
And there is a file abc.txt contains hello still there under c:.
Then I use FileUtils.writeStringToFile(...) from commons-io.jar instead, the file will be deleted.
But I don't know where is wrong with my code, please help me to find it out.
You are only closing the file if you get an IOException.
Change it to a finally block and you will be able to close and delete the file.
public static void writeFile(File file, String content) throws IOException {
OutputStream out = new FileOutputStream(file);
try {
out.write(content.getBytes("UTF-8"));
} finally {
try {
out.close();
} catch (IOException ignored) {
}
}
}
You need to close your OutputStream when you finished writing the file.
try {
out = new FileOutputStream(file);
out.write(content.getBytes("UTF-8"));
out.close();
} catch (IOException e) {
try {
out.close();
} catch (IOException e1) {
// ignored
}
}
In your main method,
public static void main(String[] args) throws IOException {
File file = new File("c:\\abc.txt");
writeFile(file, "hello");
// delete the file
boolean deleted = file.delete();
System.out.println("Deleted? " + deleted);
}
You open the file, write to it and then do not close it. Java keeps the file open for you, so if you wanted to add more information to it, you could. However, to be able to delete the file, you need to make sure no other reference is open to it. You can do this by using file.close() to close the file handle Java reserves for you.
It's best practice to always close a stream when you are done with it, especially if you added data to it. Otherwise, you might run into situations where you are keepings files open by accident, or, in extreme cases, lose data you thought was saved already.
Have a look at what FileUtils.writeStringToFile() does that you haven't.
public static void writeStringToFile(File file, String data, String encoding) throws IOException {
OutputStream out = new java.io.FileOutputStream(file);
try {
out.write(data.getBytes(encoding));
} finally {
IOUtils.closeQuietly(out);
}
}
You will note that the out stream is always closed, wheras in your example it only gets closed in your catch block if the write() throws an exception.
On Windows, files that are open by any program cannot be deleted.
You just delete your file if an exception occurs. You need to do that every time, after you opened the file.
You may want to put close into a finally block.
If you're using Java 7 I consider using a try-with-ressources block, which takes care of closing files for you.
try (BufferedReader br = new BufferedReader(new FileReader(path)))
{
return br.readLine();
}