JAVA - Writing sentences to textfile - java

I have this code below. Basically I'm getting an input from a given url. This website shows a sentence. Each time I reload the website it gets a new sentence and so on. So, I managed to get that working. Now I'm trying to write the sentence in a textfile. But something is wrong. It only writes the first line and nothing else. What's wrong with my code?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class ReadIp {
public static void main(String[] args) throws MalformedURLException, IOException,
InterruptedException {
ReadIp readIP = new ReadIp();
while (true) {
readIP.getIP();
Thread.sleep(2000);
}
}
BufferedReader buff;
InputStreamReader inStream;
String line;
URL url;
URLConnection urlConn;
FileWriter fileWriter ;
BufferedWriter bufferedWriter;
public ReadIp() throws IOException {
fileWriter = new FileWriter("myfile.txt", true);
bufferedWriter = new BufferedWriter(fileWriter);
}
public void getIP() throws MalformedURLException, IOException {
this.url = new URL("http://test.myrywebsite.co.uk");
this.urlConn = this.url.openConnection();
this.inStream = new InputStreamReader(this.urlConn.getInputStream());
this.buff = new BufferedReader(this.inStream);
try {
while ((this.line = this.buff.readLine()) != null)
{
System.out.println(this.line);
try {
this.bufferedWriter.write(this.line);
this.bufferedWriter.write("\n");
this.bufferedWriter.flush();
} catch (IOException e)
{
}
}
if (this.bufferedWriter != null)
{
this.bufferedWriter.close();
}
this.inStream.close();
}
catch (Exception ex)
{
}
}
}
Any help would be greatly appreciated.
Thank you.

Move the statement
writer.close();
out of the inner try catch block so that you're not closing the OutputStream after writing the first entry to the file. The same applys to the InputStream
inStream.close();

The BufferedWriter is being opened in the constructor and is being closed in getIp. The constructor is called only once, but getIp is called every 2 seconds to read a sentence. So the BufferedWriter is being closed after the first line (and not opened again). The second call of getIp tries to write the second sentence but the BufferedWriter is closed. This should throw an Exception which is being ignored since the catch block is empty.
Never leave a catch block empty - as fgb wrote above!
First of all, at least add a printStackTrace() to each empty catch block, e.g.:
catch (Exception ex) {
ex.printStackTrace();
}
so you can see if an Exception is being thrown...
I would suggest to open the BufferedWriter in the method getIp instead of the constructor; or, if it should stay open all the time, close the BufferedWriter in an additional method, called after the loop in main terminates

Related

FileWriter only displays the last line

When I display the variable data using System.out.println(data), it displays the content (all lines) of the "filename.txt".
However, when I use myWriter.write(data), it only writes the last line of the initial file.
My task is to read a file (in this case, filename.txt) and copy its content into a new file (new.txt).
package javaapplication13;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
public class readFile {
public static String data;
public static void main(String[] args) throws IOException{
try{
File myObj = new File("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\filename.txt");
try (Scanner myReader = new Scanner(myObj)) {
do{
data = myReader.nextLine();
}
while (myReader.hasNextLine());
PrintWriter out = new PrintWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt");
FileWriter myWriter = new FileWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt");
myWriter.write(data);
myWriter.close();
out.close();
myReader.close();
}
}
catch (FileNotFoundException e){
System.out.println("An error occurred.");
}
}
}
Every iteration of the loop opens a new writer, and then writes to it, thus overwriting the file. Instead, you should open the writer once, before the loop, and close it once you're done writing. E.g.:
try (FileWriter myWriter = new FileWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt")) {
while (myReader.hasNextLine());
myWriter.write(myReader.nextLine());
}
}

How to write String from variable to text file

My goal here is to read lines from a text file, check if they are palindromes, and then write those to a completely different file.
Now the problem, as far as I can see, lies in the if statement block where I check for palindromes successfully but can't seem to write them to another file because they are stored in a variable.
When I use the BufferedWriter write method and set the parameters as an actual string with quotes, everything works.
How can I solve this?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
public class Zadatak14 {
public static void main(String[] args) {
BufferedReader br;
try {
br = new BufferedReader(new FileReader("C:\\Users\\Luka\\Documents\\NetBeansProjects\\CS101-DZ14-14\\src\\zadatak14\\ulaz.txt"));
String line;
while ((line = br.readLine()) != null) {
String palindrome = new StringBuilder(line).reverse().toString();
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\Luka\\Documents\\NetBeansProjects\\CS101-DZ14-14\\izlaz.txt"));
if (line.contains(palindrome)) {
System.out.println(line);
bw.write(line);
}
bw.close();
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("Greska");
} catch (IOException ex) {
System.out.println("Greska");
}
}
}
BufferedWriter bw = new BufferedWriter
You're making a new writer for every line in your input, which surely you don't want. Move the creation of the writer up top, right after opening the reader.
br.close();
not how you do that. This is how you do that:
try (BufferedWriter bw = new BufferedWriter(new FileWriter("...."))) {
// code here
}
// no matter how you get out of this code, the file is closed.
The reason you do it with the above is because that bw.close() won't get called if exceptions occur, if you return out of the block. With the try construct, that stream is closed when code exits from the block no matter how it does that.
} catch (FileNotFoundException e) {
System.out.println("Greska");
Not how you do that - exceptions contain a lot of useful info (at least 4 things, more for some specific kinds of exceptions: type, message, stack trace, cause), and you're tossing it all in the garbage. It's a bad idea to toss information about problems in the bin. Don't. The right move is to add throws Exception to your public static void main(String[] args) method, and then you don't need a catch at all. If you must, the correct body for a catch block if you don't have a good way to handle the problem, is throw new RuntimeException("Uncaught", e);. This preserves all information and doesn't cause errors about having to catch exceptions.

When java program write the file using FileOutputStream, same time I paste the file, FileNotFoundException thrown

Let me explain the situation. In Windows OS.
My java program writes the logfile.
Usually It's OK, but when I copying and pasting the logfile(ctrl + c and v),
java throws exception java.io.IOException: java.io.FileNotFoundException: C:\log.txt (The process cannot access the file because it is being used by another process)
After I research the problem, I found this exception throws by pasting the file. Not copying.
Please tell me why this exception occur.
Reproduce code is below(encode "Windows-31J" is japanese, there is no
particular meaning). Excecute this program and copy and paste "C:\log.txt".
package test;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.stream.IntStream;
public class FileNotFound {
public static void main(String[] args) {
IntStream.range(0, 100000).parallel().forEach(
i -> {
try {
fileWrite("C:\\log.txt", String.valueOf(i));
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
public static void fileWrite(String filePath, String str) throws IOException {
try (FileOutputStream fw = new FileOutputStream(filePath, true);
OutputStreamWriter ow = new OutputStreamWriter(fw, "Windows-31J");
BufferedWriter bw = new BufferedWriter(ow);
PrintWriter out = new PrintWriter(bw)) {
out.println(str);
} catch (IOException e) {
throw new IOException(e);
}
}
}
It occurs because another process, i.e. your Explorer window, is using the file, via the 'copy' action, which Windows does not allow. Solution: don't.

Java : Problems accessing and writing to file

I was testing out writing to files with this code:
package files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class FileTest1
{
public static void main(String[] args)
{
try
{
try
{
File f = new File("filetest1.txt");
FileWriter fWrite = new FileWriter(f);
BufferedWriter fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
}
catch(FileNotFoundException e)
{
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
}
}
catch(IOException e)
{
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
Nothing happens when it is executed.
"This is a test!" is not written, nor the StackTrace or the "A/An [exception] occurred!"...
I don't know what's causing the problem. I have fileTest1.txt in the package right under the file...
A BufferedWriter does just that, it buffers the output before it is written to the destination. This can make the BufferedWriter faster to use as it doesn't have to write to a slow destination, like a disk or socket, straight away.
The contents will be written when the internal buffer is to full, you flush the Writer or close the writer
Remember, if you open it, you should close it...
For example...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TestFileWriter {
public static void main(String[] args) {
try {
BufferedWriter fileWrite = null;
try {
File f = new File("filetest1.txt");
System.out.println("Writing to " + f.getCanonicalPath());
FileWriter fWrite = new FileWriter(f);
fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
fileWrite.flush();
} catch (FileNotFoundException e) {
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
} finally {
try {
// Note, BufferedWriter#close will also close
// the parent Writer...
fileWrite.close();
} catch (Exception exp) {
}
}
} catch (IOException e) {
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
try {
BufferedReader br = null;
try {
File f = new File("filetest1.txt");
System.out.println("Reading from " + f.getCanonicalPath());
FileReader fReader = new FileReader(f);
br = new BufferedReader(fReader);
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
} catch (FileNotFoundException e) {
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
} finally {
try {
// Note, BufferedWriter#close will also close
// the parent Writer...
br.close();
} catch (Exception exp) {
}
}
} catch (IOException e) {
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
If you are using Java 7, you may like to take a look at try-with-resources
After
fileWrite.write("This is a test!");
you have to flush() the writer. To avoid leaking of resources you should also close() the writer (which automatically flushes it).
So you need to add:
fileWrite.close();
Use BufferedWriter.flush() and BufferedWriter.close(). Additional info here http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
You must call close() or at least flush() on the writer in order for the buffer to be really written to the file.

Can't delete the file after writing some data to it, where is wrong?

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

Categories