FileWriter only displays the last line - java

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

Related

Writing a file to java without erasing what's previously written in said file

I want to write a program that keeps what I've written in my file previously, and continually adds to it, instead of erasing it all every time I run the program.
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.Math;
class Movie_Ratings_2 {
public static void main(String[] args) {
Scanner n = new Scanner (System.in);
String fileName = "output.txt";
String x = n.nextLine();
try {
PrintWriter outputStream = new PrintWriter(fileName);
outputStream.println(x);
outputStream.close();
outputStream.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

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 - Writing sentences to textfile

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

Deleting a line that starts with a particular number in a text file

I've been trying to come up with a class that deletes a line from a text file that starts with a particular number.
What I currently have doesn't show any code errors and also runs without erros; shows "BUILD SUCCESSFUL" on netbeans, but doesn't do anything to the line, or any part of the textfile whatsoever, let alone delete the intended line.
Could anyone please look at my code and please advise me on what I might have done wrong, or is missing?
Thanks a lot in advance.
Heres my code:
package Database;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Edit {
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File("/D:/TestFile.txt/");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(line.startsWith(lineToRemove))) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Edit edit = new Edit();
edit.removeLineFromFile("/D:/TestFile.txt/", "2013001");
}
}
There is a problem with your logic ... you are saying if the line equals to itself that starts with something which will never happen unless the line only consist of the line you want to remove
if (!line.trim().equals(line.startsWith(lineToRemove))
i think needs to be just
if (!line.startsWith(lineToRemove))
Change the if condition to:
if (!line.startsWith(lineToRemove)) {
pw.println(line);
pw.flush();
}

Java How do I read and write an internal properties file?

I have a file I'm using to hold system information that my program needs on execution.
The program will read from it and write to it periodically. How do I do this? Among other problems, I'm having trouble with paths
Example
How do I read/write to this properites file if deploying application as runnable jar
Take a look at the http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
You can utilize this class to use your key=value pairs in the property/config file
Second part of your question, how to build a runnable jar. I'd do that with maven, take a look at this :
How can I create an executable JAR with dependencies using Maven?
and this :
http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
I see you're not using maven to build your project altogether
You can't write to a file that exists as part of a ZIP file... it does not exist as a file on the filesystem.
Considered the Preferences API?
To read from a file you can declare a file reader using a scanner as
Scanner diskReader = new Scanner(new File("myProp.properties"));
After then for example if you want to read a boolean value from the properties file use
boolean Example = diskReader.nextBoolean();
If you wan't to write to a file it's a bit more complicated but this is how I do it:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class UpdateAFile {
static Random random = new Random();
static int numberValue = random.nextInt(100);
public static void main(String[] args) {
File file = new File("myFile.txt");
BufferedWriter writer = null;
Scanner diskScanner = null;
try {
writer = new BufferedWriter(new FileWriter(file, true));
} catch (IOException e) {
e.printStackTrace();
}
try {
diskScanner = new Scanner(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
appendTo(writer, Integer.valueOf(numberValue).toString());
int otherValue = diskScanner.nextInt();
appendTo(writer, Integer.valueOf(otherValue + 10).toString());
int yetAnotherValue = diskScanner.nextInt();
appendTo(writer, Integer.valueOf(yetAnotherValue * 10).toString());
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static void appendTo(BufferedWriter writer, String string) {
try {
writer.write(string);
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And then write to the file by:
diskWriter.write("BlahBlahBlah");

Categories