BufferedWriter NOT writing to .txt file [JAVA] [duplicate] - java

This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
Aim: The server reads in data from a text file sent by a client. The server stores this data in another text file.
Problem: I am able to read in the text file and print it to the console however, when i run my code with the BufferedWriter and open the new textfile after, the file is empty. I am not entirely sure whether i have used the BufferedWriter function incorrectly or if i am missing any key functions out?
Code:
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while (true) {
fromUser = stdIn.readLine();
if (fromUser != null) {
FileReader file = new FileReader("client-temp.txt");
BufferedReader tc = new BufferedReader(file);
BufferedWriter bw = new BufferedWriter(new FileWriter("datastore.txt"));
String line;
while ((line = tc.readLine()) != null)
{
String[] data = line.split(",");
String sensortype = data[0];
String date = data[1];
String time = data[2];
String reading = data[3];
String newdata = sensortype + date + time + reading;
System.out.println(line);
if (line != null)
{
out.write(line);
out.flush();
}
System.out.println("Data sent to file");
}
System.out.println(EmsClientID + " sending " + fromUser + " to EmsServer");
out.println(fromUser);
}
fromServer = in.readLine();
System.out.println(EmsClientID + " received " + fromServer + " from EmsServer");
}

You never call flush or close on the instance of BufferedWriter, in fact, you ignore it completely. Also, you resource management is none existent. If you open a resource, you should close it.
For example...
FileReader file = new FileReader("client-temp.txt");
try (BufferedReader tc = new BufferedReader(file)) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("datastore.txt"))) {
String line;
while ((line = tc.readLine()) != null)
{
String[] data = line.split(",");
String sensortype = data[0];
String date = data[1];
String time = data[2];
String reading = data[3];
String newdata = sensortype + date + time + reading;
System.out.println(line);
if (line != null)
{
bw.write(line);
bw.newLine();
}
System.out.println("Data sent to file");
}
} catch (IOException exp) {
exp.printStackTrace();
}
} catch (IOException exp) {
exp.printStackTrace();
}
See The try-with-resources Statement for more details
(ps: You can compound the try-with-resource statement, opening multiple resources within the same try (...) { section, but I wanted to demonstrate the basic concept)

Your code is incomplete. I'm gonna go out on a whim here and assume your problem.
Add
out.close();
at the end of your code.

Related

How to read file from network path?

Basic explanation:
I'm coding a simple java utility which will take xml file and convert it into html. All xml files have same structure and need to be converted into same looking HTML file so i chose to code it using BufferedReader and Writer, see code below.
I'm having following problem If i'm using file that is on local disk, than there is no problem and everything workes fine, but when i try to use file that is on connected shared network disk, code throws exception.
this is whole code
reading and writting file that is stored in project folder workes just fine and just as i want to, i'm only having problem with file stored on network disk.
public static void main(String[] args) {
String cestaKsuboruXml = "file.xml"; //workes fine
//this one throws error
// String cestaKsuboruXml = "\\172.27.20.38\eDesk\2017\0925\144f7d8d-3786-4858-95ef-bb853c41b713\1_PridelenieCislaPodania.xml";
//class which contains html code
sablonaJedna sablonaJedna = new sablonaJedna();
String fileName = null ;
String line = null;
StringBuilder text = new StringBuilder();
StringBuilder subject = new StringBuilder();
try {
FileReader fileReader = new FileReader(cestaKsuboruXml);
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(new FileInputStream(cestaKsuboruXml), "UTF-8"));
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("<subject>")) {
subject.append(line);
}
if (!line.contains("<GeneralAgenda") && !line.contains("<subject>"))
{
text.append(line);
}
}
} catch (IOException ex) {
System.out.println("Exception");
}
String text2 = text.toString();
String subject2 = subject.toString();
subject2 = subject2.replace("<subject>", "");
subject2 = subject2.replace("</subject>", "");
text2 = text2.replace("<text>", "");
text2 = text2.replace("</text>", "");
text2 = text2.replace("</GeneralAgenda>", "");
try {
BufferedWriter writer = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream("vvvaa.html", true), "UTF-8"));
writer.write(sablonaJedna.getSablonaCss() + sablonaJedna.getSablonaHtml() + subject2 +
"</span></div><div class=\"clear\"> </div><div><label class=\"labelVis\">Text: </label> <span class=\"contentVis wordwrap\">"
+ text2 + "</span></div><div class=\"clear\"> </div></div></div></body></html>"
);
writer.close();
} catch (IOException xx) {
System.out.println("Exception");
}
}
all i had to do was use this as a source:
String cestaKsuboruXml = "\\\\172.27.20.38\\eDesk\\2017\\0925\\144f7d8d-3786-4858-95ef-bb853c41b713\\1_PridelenieCislaPodania.xml";
so two more backslashes at the start of a link

Trying to replace a symbol in a text file of 4000 lines, ends up with only 500 in Java

What i'm trying to do, is to replace a symbol in a file text which contains over 4000 lines but using the below code, after the program ends, it only remain 500 lines. Why is this file truncated? How to solve this?
This is my code:
ArrayList<String> arrayList = new ArrayList<>();
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {System.err.println(e);}
}
} catch (Exception e) {e.printStackTrace();}
Thanks in advance!
new BufferedWriter(new FileWriter(file)) clear file.
You should open it only once. Also you reading and writing to the same file. You should use different files.
Like this
try (FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
bw.write(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
You are writing to the same file while you are reading it. This won't work. Once you start writing, the file becomes empty (plus whatever you've written), so subsequent reads will report end-of-file. Your ~500 lines will be buffered input from the first read.
One solution is to do all the reading first, before opening the file again for writing:
Array<String> arrayList = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
while ((String line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {
System.err.println(e);
}
Here, first the program slurps the file into a List<String>, fixing the lines as it goes. Then it writes all the lines back out to the file.
There are circumstances in which this model is appropriate. For example, you might be building a non-linear data structure from the file content. Or you might need to see the last line before you can modify earlier lines (and be unable to re-open the data source from the start).
However I'd suggest a method that's more thrifty with memory. You don't need to keep all those lines in memory. You can read one line, fix it up, then forget about it. But to do this, you'll need to write to a second file.
String filein = "inputfile";
String fileout = filein + ".tmp";
try(
BufferedReader reader = new BufferedReader(new FileReader(filein));
Writer writer = new BufferedWriter(FileWriter(fileout))
) {
while ((String line = bufferedReader.readLine()) != null) {
writer.write(line.replace("þ", "t");
}
}
Files.move(Paths.get(fileout)),
Paths.get(filein),
CopyOption.REPLACE_EXISTING);
I have left out the necessary exception catching -- add back in as required.

File Writer that puts a number of a line before the line it's about to write

I am writing a method for my java class. it looks like this so far:
String file_name;
String line;
void addLine(file_name, line){
int line_number;
try {
FileWriter writer = new FileWriter(file_name, true);
PrintWriter out = new PrintWriter(writer);
out.println(line_number + line);
}
catch (IOException e){
System.out.println(e);
}
}
How should I define line_number so it would check how many lines were there in file before I printed out next into it?
int totalLines = 0;
BufferedReader br br = new BufferedReader(new FileReader("C:\\filename.txt"));
String CurrentLine = "";
while ((CurrentLine = br.readLine()) != null) {
++totalLines
}
i think you have to actually read the file by using a bufferedreader. and then keep on incrementing the totalLines till it reach the end of the file
You can count them with a function posted here: Number of lines in a file in Java
They tested it with a 150 MB log file and it seems to be fast.

Why can't I neither delete nor rename the file?

While creating a method to my class, I got an unexpected problem. I've tried solutions from other theards, but they just don't work for me. My method should simply find the line specified, copy the file skipping unnecessary line, delete the original file and rename temporary file to the name of original file. It succesfuly creates new file as expected, but then fails to delete previous one as it fails to rename temporary file to original. I can't figure out, why?
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
File filePath = new File(path);
BufferedReader reader = new BufferedReader(new FileReader(file_name + ".txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
filePath.delete();
temp.renameTo(theFile);
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
Try this code:
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
BufferedReader reader = new BufferedReader(new FileReader(theFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
theFile.delete();
temp.renameTo(file_name + ".txt");
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
I could suggest a couple of reasons why the delete and/or rename might fail, but there is a better way to solve your problem than guessing1.
If you use Path and the Files.delete(Path) and Files.move(Path, Path, CopyOption...) methods, they will throw exceptions if the operations fail. The exception name and message should give you clues as to what is actually going wrong.
The javadoc is here and here.
1 - Here are a couple of guesses: 1) the file has been opened elsewhere, and it is locked as a result. 2) You don't have access to delete the file.

How to delete a line from text line by id java

How to delete a line from a text file java?
I searched everywhere and even though I can't find a way to delete a line.
I have the text file: a.txt
1, Anaa, 23
4, Mary, 3
and the function taken from internet:
public void removeLineFromFile(Long id){
try{
File inputFile = new File(fileName);
File tempFile = new File("C:\\Users\\...myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = Objects.toString(id,null);
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
String trimmLine[] = trimmedLine.split(" ");
if(!trimmLine.equals(lineToRemove)) {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
}catch (IOException e){
e.printStackTrace();
}
}
where the fileName is the path for a.txt.
I have to delete the line enetering the id.That's why I split the trimmedLine. At the end of execution I have 2 files, the a.txt and myTempFile both having the same lines(the ones from beginning). Why couldn't delete it?
If I understand your question correctly, you want to delete the line whose id matches with the id passed in the removeLineFromFile method.
To make your code work, only few changes are needed.
To extract the id, you need to split using both " " and ","
i.e.
String trimmLine[] = trimmedLine.split(" |,");
where | is the regex OR operator.
See Java: use split() with multiple delimiters.
Also, trimmLine is an array, you can't just compare trimmLine with lineToRemove. You first need to extract the first part which is the id from trimmLine. I would suggest you to look at the working of split method if you have difficulty in understanding this. You can have a look at How to split a string in Java.
So, extract the id which is the first index of the array trimmLine here using:
String part1 = trimmLine[0];
and then compare part1 with lineToRemove.
Whole code looks like:
public void removeLineFromFile(Long id){
try{
File inputFile = new File(fileName);
File tempFile = new File("C:\\Users\\...myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = Objects.toString(id,null);
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
String trimmLine[] = trimmedLine.split(" |,");
String part1 = trimmLine[0];
if(!part1.equals(lineToRemove)) {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
}catch (IOException e){
e.printStackTrace();
}
}

Categories