import java.io.*;
class C{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("C.java");
FileOutputStream fout=new FileOutputStream("M.java");
int i=0;
while((i=fin.read())!=-1){
fout.write((byte)i);
}
fin.close();
}
}
I try create file to read and write from where the code will be stored. In my case it was stored in C drive (my program thats I created it there only read and write file).
My program builds successfully but no output
application name - javaprogram
package name- pack
Inside package I have placed two files c.txt and m.txt
I even want to know how is that we have .java file (I was trying with c.txt and m.txt rather than .java)
This IS WHAT I GET ERROR
init:
deps-jar:
Compiling 1 source file to C:\Users\user\Documents\NetBeansProjects\JavaApplication1\build\classes
compile-single:
run-single:
Exception in thread "main" java.io.FileNotFoundException: file (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at javaapplication1.C.main(C.java:20)
Use the code below you are missing something file object
class C {
public static void main(String args[])
{
try
{
File f1 = new File("C.java");
File f2 = new File("M.java");
FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read()) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Another elegant way of doing that is
download Commons IO from this Link and add it to your project library then use the code below.
class C {
public static void main(String args[]) throws Exception
{
try
{
File f1 = new File("C.java");
File f2 = new File("M.java");
FileUtils.copyFile(f1, f2);
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
} }
Related
This sample is supposed to locate the copied over .zip file from the build output directory but for some reason it doesn't find that file. I created a resource directory in the root directory and marked it as "Resource Root" and still didn't work. Any help is appreciated. Here is a snippet of the code:
if (install && package == null) {
File file = new File("file.zip");
byte[] bytes = new byte[(int) file.length()];
try {
FileInputStream inputStream = new FileInputStream(file);
inputStream.read(bytes);
inputStream.close();
}
catch (FileNotFoundException ex) {
System.out.println("File Not Found.");
return;
}
catch (IOException ex) {
System.out.println("Error Reading The File.");
ex.printStackTrace();
}
Here is a screenshot of the project structure:
Project Structure
I suppose you mean you've created the file in the /main/resources folder of your project?
If that's so, then you can copy it as such:
public static void main(String[] args) throws IOException {
var path = Main.class.getResourceAsStream("/myfile.txt");
Files.copy(path, Path.of("file.txt"));
}
My compression class works incorrectly. When i am trying to compress simple file that contains sentence "something", compressed and uncompressed returns something other. Here is my deflating code:
public static void inflate(String arg) throws Exception {
try {
FileInputStream fin = new FileInputStream(arg);
InflaterInputStream in = new InflaterInputStream(fin);
FileOutputStream fout = new FileOutputStream("def.txt");
int i;
while ((i = in.read()) != -1) {
fout.write((byte) i);
fout.flush();
}
fin.close();
fout.close();
in.close();
} catch (Exception e) {
System.out.println(e);
}
new File(arg).delete();
new File("def.txt").renameTo(new File(arg));
}
public static void deflate(String arg) throws Exception {
try {
FileInputStream fin = new FileInputStream(arg);
FileOutputStream fout = new FileOutputStream("def.txt");
DeflaterOutputStream out = new DeflaterOutputStream(fout);
int i;
while ((i = fin.read()) != -1) {
out.write((byte) i);
out.flush();
}
fin.close();
out.close();
} catch (Exception e) {
System.out.println(e);
}
new File(arg).delete();
new File("def.txt").renameTo(new File(arg));
}
I call it using
public static void main(String[] args) {
try {
Main.deflate(args[0]);
Main.inflate(args[0]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So how to fix my code? I think that problem is not in deflating code.
Your code does seem to work as expected.
Running it on a text file containing the word 'something' returns an identical file.
To confirm that the output is the same, try editing the following lines:
Test.inflate("def.txt");
which is in your main function and
FileOutputStream fout = new FileOutputStream("output.txt");
from your inflate function.
Then comment out the following lines in both your deflate() and inflate() functions
//new File(arg).delete();
//new File("def.txt").renameTo(new File(arg));
The program will now take an input file, I used input.txt with the word 'something' as per your example, and create a deflated file def.txt and an output.txt file that is created by inflating def.txt.
The output file should match the input file exactly, while the deflated file should be different. If not, there must be some further information about the program that is missing.
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);
}
}
}
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.
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)
{
}
}
}