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
Related
I m trying to write ArrayList data in to the Text file using this code:
public PrintWriter w() {
try {
FileWriter f = new FileWriter("C:\\Users\\jon\\Desktop\\a.txt");
PrintWriter br = new PrintWriter(f);
return br;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
return null;
}
for (String g : a) {
try {
PrintWriter br = w();
br.println(g);
System.out.print(" " + g);
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1);
}
But it is not writing the data to the text file. Can anyone help me see the problem?
Here it is:
public static BufferedWriter w() throws IOException{
File file = new File("D:\\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);
return bw;
}
and this is what you need to call from your for loop:
for (String g : a) {
try {
BufferedWriter bw = w();
bw.write(g);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
Am using nio2 to read the external file in my desktop using eclipse. I am getting the exception for the following code.
"java.nio.file.NoSuchFileException: C:\Users\User\Desktop\JEE\FirstFolder\first.txt"
Kindly advise how to resolve it? Tried using command prompt also. Getting the same exception.
public class ReadingExternalFile {
public static void main(String[] args) {
Path p1= Paths.get("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
System.out.println(p1.toString());
System.out.println(p1.getRoot());
try(InputStream in = Files.newInputStream(p1);
BufferedReader reader = new BufferedReader(new InputStreamReader(in)))
{
System.out.println("Inside try");
String line=null;
while((line=reader.readLine())!=null){
if (!line.equals("")) {
System.out.println(line);
}
//System.out.println(line);
}
} catch (IOException e) {
System.out.println( e);
}
}
}
I dont understand why you are using a Path object, you can simply make the file using the File object and just using the string as the path, and then wraping it in a file reader object then wrapping that in a buffered reader, the end should look something like this:
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
System.out.println(bfr.readLine());
bfr.close();
} catch (IOException e){
e.printStackTrace();
}
}
don't forget to close your streams after reading and writing, also use readable names (don't do what I've done, use meaningful names!)
Try below code hope this will help you.
Path p1= Paths.get("C:\\Users\\user\\Desktop\\FirstFolder\\first.txt");
try(
BufferedReader reader = Files.newBufferedReader(p1, Charset.defaultCharset()))
{
System.out.println("Inside try");
String line=null;
while((line=reader.readLine())!=null){
if (!line.equals("")) {
System.out.println(line);
}
//System.out.println(line);
}
} catch (IOException e) {
System.out.println( e);
}
Try this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
FileReader freader = new FileReader(file);
BufferedReader bufreader = new BufferedReader(freader);
System.out.println(bufreader.readLine());
bufreader.close();
} catch (IOException e){
e.printStackTrace();
}
}
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();
}
}
}
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();
}
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>