Output stream doesn't print anything - java

public class Demo
{
public static void main(String[] args)
{
PrintWriter outputStream= null;
try
{
outputStream = new PrintWriter (new BufferedWriter(new PrintWriter("text.txt")));
}
catch(FileNotFoundException e)
{
System.out.println("Error");
System.exit(0);
}
finally {
if (outputStream!= null)
outputStream.close();
}
outputStream.println("Hahahahaha");
}
}
So I was given this sample code, but strangely it doesn't work at all, because when I open the text file. It's completely blank. How's that possible? Is it because of the output.close? I commented that part out, but it still doesn't work.

Why use:
outputStream = new PrintWriter (new BufferedWriter(new PrintWriter("text.txt")));
Why not just use:
PrintWriter outputStream = new PrintWriter("text.txt");

Write your println statement before closing the stream
public class Demo
{
public static void main(String[] args)
{
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter (new BufferedWriter(new PrintWriter("text.txt")));
outputStream.println("Hahahahaha");
}
catch(FileNotFoundException e)
{
System.out.println("Error");
System.exit(0);
}
finally {
if (outputStream != null)
outputStream.close();
}
}
}

You're closing outputStream before writing to it.
Note that the finally block always executes when the try block exits.
So you have to write to outputStream before exiting the try block.
Close it and you'll see the text you entered.
try
{
outputStream = new PrintWriter (new BufferedWriter(new PrintWriter("text.txt")));
outputStream.println("Hahahahaha");
}
catch(FileNotFoundException e)
{
System.out.println("Error");
System.exit(0);
}
finally {
if(outputStream != null)
outputStream.close();
}

Related

Making Java I / O and change the file to split in java

I'm making a project where using java I / O
I have a file with the following data:
170631|0645| |002014 | 0713056699|000000278500
155414|0606| |002014 | 0913042385|000001220000
000002|0000|0000|00000000000|0000000000000000|000000299512
and the output I want is as follows:
170631
0645
002014
file so that the data will be decreased down
and this is my source code:
public class Tes {
public static void main(String[] args) throws IOException{
File file;
BufferedReader br =null;
FileOutputStream fop = null;
try {
String content = "";
String s;
file = new File("E:/split/OUT/Berhasil.RPT");
fop = new FileOutputStream(file);
br = new BufferedReader(new FileReader("E:/split/11072014/01434.RPT"));
if (!file.exists()) {
file.createNewFile();
}
while ((s = br.readLine()) != null ) {
for (String retVal : s.split("\\|")) {
String data = content.concat(retVal);
System.out.println(data.trim());
byte[] buffer = data.getBytes();
fop.write(buffer);
fop.flush();
fop.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want is to generate output as above from the data that has been entered
File Input -> Split -> File Output
thanks :)
I think you forgot to mention what problem are you facing. Just by looking at the code it seems like you are closing the fop(FileOutputStream) every time you are looping while writing the split line. The outputStream should be closed once you have written everything, outside the while loop.
import java.io.*;
public class FileReadWrite {
public static void main(String[] args) {
try {
FileReader inputFileReader = new FileReader(new File("E:/split/11072014/01434.RPT"));
FileWriter outputFileWriter = new FileWriter(new File("E:/split/11072014/Berhasil.RPT"));
BufferedReader bufferedReader = new BufferedReader(inputFileReader);
BufferedWriter bufferedWriter = new BufferedWriter(outputFileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
for (String splitItem : line.split("|")) {
bufferedWriter.write(splitItem + "\n");
}
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Copying the Contents of One text file to Another in Java

I am trying to copy the contents of one text file ("1.txt") which contains 2-3 integer numbers (ex: 1 2 3) to another text file ("2.txt") but I am getting the following error upon compilation
import java.io.*;
class FileDemo {
public static void main(String args[]) {
try {
FileReader fr=new FileReader("1.txt");
FileWriter fw=new FileWriter("2.txt");
int c=fr.read();
while(c!=-1) {
fw.write(c);
}
} catch(IOException e) {
System.out.println(e);
} finally() {
fr.close();
fw.close();
}
}
}
Command prompt:-
C:\Documents and Settings\Salman\Desktop>javac FileDemo.java
FileDemo.java:20: error: '{' expected
finally()
^
FileDemo.java:20: error: illegal start of expression
finally()
^
FileDemo.java:20: error: ';' expected
finally()
^
FileDemo.java:27: error: reached end of file while parsing
}
^
4 errors
But upon checking the code, I find that the finally() block is properly closed.
It's finally, not finally():
try {
//...
} catch(IOException e) {
//...
} finally {
//...
}
By the way, you have an endless loop there:
int c=fr.read();
while(c!=-1) {
fw.write(c);
}
You must read the data inside the loop in order to let it finish:
int c=fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
In the finally block, your fr and fw variables can't be found since they're declared in the scope of the try block. Declare them outside:
FileReader fr = null;
FileWriter fw = null;
try {
//...
Now, since they are initialized with null value, you must also do a null check before closing them:
finally {
if (fr != null) {
fr.close();
}
if (fw != null) {
fw.close();
}
}
And the close method on both can throw IOException that must be handled as well:
finally {
if (fr != null) {
try {
fr.close();
} catch(IOException e) {
//...
}
}
if (fw != null) {
try {
fw.close();
} catch(IOException e) {
//...
}
}
}
In the end, since you don't want to have a lot of code to close a basic stream, just move it into a method that handles a Closeable (note that both FileReader and FileWriter implements this interface):
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
//...
}
}
In the end, your code should look like:
import java.io.*;
class FileDemo {
public static void main(String args[]) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("1.txt");
fw = new FileWriter("2.txt");
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
//...
}
}
}
Since Java 7, we have try-with-resources, so code above could be rewritten like:
import java.io.*;
class FileDemo {
public static void main(String args[]) {
//this will close the resources automatically
//even if an exception rises
try (FileReader fr = new FileReader("1.txt");
FileWriter fw = new FileWriter("2.txt")) {
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
More efficient way is...
public class Main {
public static void main(String[] args) throws IOException {
File dir = new File(".");
String source = dir.getCanonicalPath() + File.separator + "Code.txt";
String dest = dir.getCanonicalPath() + File.separator + "Dest.txt";
File fin = new File(source);
FileInputStream fis = new FileInputStream(fin);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
FileWriter fstream = new FileWriter(dest, true);
BufferedWriter out = new BufferedWriter(fstream);
String aLine = null;
while ((aLine = in.readLine()) != null) {
//Process each line and add output to Dest.txt file
out.write(aLine);
out.newLine();
}
// do not forget to close the buffer reader
in.close();
// close buffer writer
out.close();
}
}
Its a compilation error
public static void main(String args[])
{
try
{
FileReader fr=new FileReader("1.txt");
FileWriter fw=new FileWriter("2.txt");
int c=fr.read();
while(c!=-1)
{
fw.write(c);
}
}
catch(IOException e)
{
System.out.println(e);
}
finally // finally doesn't accept any arguments like catch
{
fr.close();
fw.close();
}
}
A Finally block shouldn't have the round parentheses.
Try:
import java.io.*;
class FileDemo
{
public static void main(String args[])
{
try
{
FileReader fr=new FileReader("1.txt");
FileWriter fw=new FileWriter("2.txt");
int c=fr.read();
while(c!=-1)
{
fw.write(c);
c = fr.read(); // Add this line
}
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
fr.close();
fw.close();
}
}
}
Check this javapractices you will get better idea.
it will help u to understand more about try catch finally.
import java.io.*;
class FileDemo
{
public static void main(String args[])throws IOException
{
FileReader fr=null;
FileWriter fw=null;
try
{
fr=new FileReader("1.txt");
fw=new FileWriter("2.txt");
int c=fr.read();
while(c!=-1)
{
fw.write(c);
}
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
fr.close();
fw.close();
}
}
}
1.your code is not correct > finally block does not takes parenthesis ahead if it. 2.parenthesis always comes in front of methods only.
3.dear your Scope of FileReader and FileWrier objects are end with in the try blocks so you will get one more error in finally block that is fw not found and fr not found
4."throws IOEXception" also mention front of main function
I see it is way old thread but writing it as many people still be using the above ways.
If you are using Java9 or above then I think, can look for below simple way -
try(FileInputStream fis = new FileInputStream("e:/file1");
FileOutputStream fos = new FileOutputStream("e:/file2");) {
fis.transferTo(fos);
} catch(Exception e) {
e.printStackTrace();
}
For me above code copied 2GB data in 50sec to new file.
If you need better performance then can check other ways.
public class Copytextfronanothertextfile{
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = null;
FileWriter fw = null;
try{
fr = new FileReader("C:\\Users\\Muzzammil\\Desktop\\chinese.txt");
fw = new FileWriter("C:\\Users\\Muzzammil\\Desktop\\jago.txt");
int c;
while((c = fr.read()) != -1){
fw.write(c);
}
}finally{
if (fr != null){
fr.close();
}
if(fw != null){
fw.close();
}
}
}
}
Try this code:
class CopyContentFromToText {
public static void main(String args[]){
String fileInput = "C://Users//Adhiraj//Desktop//temp.txt";
String fileoutput = "C://Users//Adhiraj//Desktop//temp1.txt";
try {
FileReader fr=new FileReader(fileInput);
FileWriter fw=new FileWriter(fileoutput);
int c;
while((c=fr.read())!=-1) {
fw.write(c);
}
fr.close();
fw.close();
}
catch(IOException e) {
System.out.println(e);
}
}
}

Writing to a file in Java. Help me code

I am passing a file path to this method which writes the in txt file. But when I run this program it is not writing full and I don't know where I made mistake.
public void content(String s) {
try {
BufferedReader br=new BufferedReader(new FileReader(s));
try {
String read=s;
while((read = br.readLine()) != null) {
PrintWriter out = new PrintWriter(new FileWriter("e:\\OP.txt"));
out.write(read);
out.close();
}
} catch(Exception e) { }
} catch(Exception e) { }
}
You shouldn't create your PrintWriter inside the loop every time:
public void content(String s) {
BufferedReader br=new BufferedReader(new FileReader(s));
try {
PrintWriter out=new PrintWriter(new FileWriter("e:\\OP.txt"));
String read=null;
while((read=br.readLine())!=null) {
out.write(read);
}
} catch(Exception e) {
//do something meaningfull}
} finally {
out.close();
}
}
Aditionally, as others have mentioned add a finally block, do not silently catch the exception, and follow the Java Coding Conventions.
close your PrintWriter inside finally block out side the loop
finally {
out.close();
}
It's better to use Apache Commons IO instead.
http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html should make the trick.
(Unless you are trying to learn the low-level stuff or actually knows why you can't use IOUtils for this case.)
try this
public void content(String s) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(s));
PrintWriter pr = new PrintWriter(new File("e:\\OP.txt"))) {
for (String line; (line = br.readLine()) != null;) {
pr.println(line);
}
}
}
Your closing stream before finishing it. So either put it into
<code>
finally {
out.close();
}
</code>
or see this simple example
<code>try {
String content = s;
File file = new File("/filename.txt");
// 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();
}
}
</code>

Why does the integer written to a file get read as a different value?

I've got a program where I need to generate an integer, write it to a text file and read it back the next time the program runs. After some anomalous behavior, I've stripped it down to setting an integer value, writing it to a file and reading it back for debugging.
totScore, is set to 25 and when I print to the console prior to writing to the file, I see a value of 25. However, when I read the file and print to the console I get three values...25, 13, and 10. Viewing the text file in notepad gives me a character not on the keyboard, so I suspect that the file is being stored in something other that int.
Why do I get different results from my write and read steps?
Is it not being written as an int? How are these values being stored in the file? Do I need to cast the read value as something else and convert it to an integer?
Consider:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.file.*;
import java.nio.file.StandardOpenOption.*;
//
public class HedgeScore {
public static void main(String[] args) {
int totScore = 25;
OutputStream outStream = null; ///write
try {
System.out.println("totscore="+totScore);
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("hedgescore.txt")));
bw.write(totScore);
bw.write(System.getProperty("line.separator"));
bw.flush();
bw.close();
}
catch(IOException f) {
System.out.println(f.getMessage());
}
try {
InputStream input = new FileInputStream("hedgescore.txt");
int data = input.read();
while(data != -1) {
System.out.println("data being read from file :"+ data);
data = input.read();
int prevScore = data;
}
input.close();
}
catch(IOException f) {
System.out.println(f.getMessage());
}
}
}
You're reading/writing Strings and raw data, but not being consistent. Why not instead read in Strings (using a Reader of some sort) and then convert to int by parsing the String? Either that or write out your data as bytes and read it in as bytes -- although that can get quite tricky if the file must deal with different types of data.
So either:
import java.io.*;
public class HedgeScore {
private static final String FILE_PATH = "hedgescore.txt";
public static void main(String[] args) {
int totScore = 25;
BufferedWriter bw = null;
try {
System.out.println("totscore=" + totScore);
bw = new BufferedWriter(new FileWriter(new File(
FILE_PATH)));
bw.write(totScore);
bw.write(System.getProperty("line.separator"));
bw.flush();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
InputStream input = null;
try {
input = new FileInputStream(FILE_PATH);
int data = 0;
while ((data = input.read()) != -1) {
System.out.println("data being read from file :" + data);
}
input.close();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
or:
import java.io.*;
public class HedgeScore2 {
private static final String FILE_PATH = "hedgescore.txt";
public static void main(String[] args) {
int totScore = 25;
PrintWriter pw = null;
try {
System.out.println("totscore=" + totScore);
pw = new PrintWriter(new FileWriter(new File(FILE_PATH)));
pw.write(String.valueOf(totScore));
pw.write(System.getProperty("line.separator"));
pw.flush();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (pw != null) {
pw.close();
}
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(FILE_PATH));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Java: PrintWriter

I am trying to use PrintWriter.java but I am getting a rather strange problem and I am not able to figure out what am I am missing here.
MyPrintWriter.java
public class MyPrintWriter {
public static void main(String[] args) {
File myFile = new File("myFileDirectory/myFileName.txt");
try {
FileWriter fw = new FileWriter(myFile);
PrintWriter pw = new PrintWriter(fw);
pw.println("Hello World!");
pw.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " + myFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
MyFileWriter.java
public class MyFileWriter {
public static void main(String[] args) {
File myFile = new File("myFileDirectory/myFileName.txt");
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
FileWriter fw = new FileWriter(myFile);
PrintWriter pw = new PrintWriter(fw);
String input;
input = br.readLine();
while(input != null) {
pw.println(input);
input = br.readLine();
}
br.close();
pw.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " + myFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
MyPrintWriter.java is happily writing to the myFileName.txt file but MyFileWrite.java can't.
Could someone help me understand what am I missing here?
You probably need to flush your print writer.
The PrintWriter constructor with a FileWriter parameter creates a PrintWriter with autoFlush set to off
Calling pw.flush() before pw.close(); should do the trick

Categories