Java Input Output Stream can't read the file - java

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

Related

Convert text file data into uppercase in Java

I made the program in java to convert the text in the file in the uppercase but it erases data instead of converting it
But when I take data from 1 file and write converted data into another file, it works fine.
So I got problem that how can I do this using single file.
Here below is my code, Tell me how to correct this?
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
public class uppercase{
public static void main(String[] args) {
try {
FileReader reader = new FileReader("e.txt");
FileWriter writer = new FileWriter("e.txt");
int data;
int data2;
while((data=reader.read())!= -1) {
data2=Character.toUpperCase(data);
writer.write(data2);
}
reader.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is bad idea, because you are writing to same file you are reading from. You should either:
Load complete file to memory, close it and then dump it to same file.
Save to different file and rename (better)
firstly you open a stream to read from file and append the result to a String variable and at the end of reading, you write all the data to the file:
try {
FileReader reader = new FileReader("e.txt");
String result = "";
int data;
int data2;
while ((data = reader.read()) != -1) {
data2 = Character.toUpperCase(data);
result += (char)data2;
}
reader.close();
System.out.println(result);
FileWriter writer = new FileWriter("e.txt");
writer.write(result);
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Output file is only showing last line of the input file

In the output file "CMFTSwitchesnew.txt" only has the last line of the input file. I've tested a few different methods such as changing write.println(input.nextLine()) but I'm not sure now where the issue is.
package WorkingWithFiles;
import java.io.*;
import java.util.Scanner;
public class FileIO
{
public static void main(String[] args)
{
File output = new File("CMFTSwitchesNew.txt");
File source = new File("src/CMFTSwitches.txt");
try {
Scanner input = new Scanner(source);
while (input.hasNextLine()) {
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
}
} catch (FileNotFoundException e) {
System.out.println("The file was not found");
}
}
}
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
You're creating a PrintWriter in each iteration without using the constructor that allows you to tell the PrintWriter to append data at the end of an already existing file. That way you only see the output of the last time the file was written. Either change that to
PrintWriter write = new PrintWriter(output, true);
or instantiate the PrintWriter outside the while-loop and close it after it.

Java System.out to both screen and file simultaneously, and programatically [duplicate]

I found the code below from the internet, works but it doesn't write the printed console to omt.txt, it only writes the System.out.println statements after the second catch block.If you run the code once you will understand what I mean.All I want is to write what is on console to the "omt.txt" file that is all...
After some answers, I see that my question wasn't clear, sorry for that.
I want to save console output to omt.txt text file. If on the console "Hello 123" is printed , it should be also in omt.txt file.In other words whatever on the console is printed should be simultaneously written on the om.txt file or can be after the console execution but should be 1-to-1 the same!
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class Wrt_file {
public static void main(String[] args) {
System.out.println("THIS is what I see on the console. but not on TEXT file");
File f = new File("omt.txt");
if(!f.exists())
{
try {
f.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
FileOutputStream fos = new FileOutputStream(f);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("THIS is what I see on the text file, but not on CONSOLE");
for (int i=0; i<10; i++){
System.out.println("Testing");
}
}
}
Updated answer after learning that OP wants to duplicate streams
Since you want to write data in both streams try using TeeOutputStream from Apache Commons. Change your code in second try to
try {
FileOutputStream fos = new FileOutputStream(f);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
fos.flush();
}
catch (Throwable t) {
// Ignore
}
}, "Shutdown hook Thread flushing " + f));
//we will want to print in standard "System.out" and in "file"
TeeOutputStream myOut=new TeeOutputStream(System.out, fos);
PrintStream ps = new PrintStream(myOut, true); //true - auto-flush after println
System.setOut(ps);
} catch (Exception e) {
e.printStackTrace();
}
Now results from System.out will also be placed in your file.
The reason is :
The java.lang.System.setOut() method reassigns the "standard" output stream.
so when you use System.out.println it will print only in the text file
So , if you want to print on the text file and on the console , Try this :
   
FileOutputStream fos = new FileOutputStream(f);
    PrintStream ps = new PrintStream(fos);
ps.println("THIS is what I see on the text file, but not on CONSOLE");
System.out.println("THIS is what I see on the text file, but not on CONSOLE");
for (int i = 0; i < 4; i++) {
ps.println("Testing");
System.out.println("Testing");
}
My solution to this problem is to simply define your own PrintStream which overrides the methods you are using:
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class DualStream extends PrintStream {
public PrintStream consoleOutput = null;
public PrintStream fileOutput = null;
public DualStream(final PrintStream consoleOutput, final PrintStream fileOutput) throws FileNotFoundException {
super(fileOutput, true);
this.consoleOutput = consoleOutput;
this.fileOutput = fileOutput;
}
#Override
public void println() {
consoleOutput.println();
super.println();
}
#Override
public void println(final Object output) {
consoleOutput.println(output);
super.println(output);
}
#Override
public void println(final String output) {
consoleOutput.println(output);
super.println(output);
}
#Override
public PrintStream printf(final String output, final Object... variables) {
consoleOutput.printf(output, variables);
super.printf(output, variables);
return this;
}
}
Every method we don't override will default to writting the output to the file only. (To default to console you can switch 1 line in the Constructor or switch both printstreams position in the constructor call)
Now simply define 2 printstreams, one of which will be writting to your file, let's make it a bufferedoutputstream to ensure good performance aswell:
public static void outputFile(final String file) {
PrintStream CombinedOutput = null;
try {
CombinedOutput = new DualStream(System.out, new PrintStream(new BufferedOutputStream(new FileOutputStream(file))));
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
System.setOut(CombinedOutput);
}
In System.java, this is the declaration of the out property:
public final static PrintStream out
You'll see that it can only be one PrintSteam object at a time. So it's either the console or the file, but not both.
At this line, you have effectively re-channelled the destination:
System.setOut(ps);
So your output stops displaying on the console.

My deflater class works incorecctly

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.

Where do i have to put input file in eclipse(java) in order to write into it

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)
{
}
}
}

Categories