Deleting an element from a text file - java

I have created a text file named 'Month.txt' which contains this String: "January February March".
This is my program below which deletes "February" from the text file:
import java.io.*;
import java.util.*;
class Delete_element_from_txtfile
{
public static void main()throws IOException
{
FileReader fr=new FileReader("Month.txt");
BufferedReader br=new BufferedReader(fr);
FileWriter fw=new FileWriter("Month.txt");
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
String str;
String newstr="";
while((str=br.readLine())!=null)
{
StringTokenizer S=new StringTokenizer(str);
while(S.hasMoreTokens()==true)
{
String month=S.nextToken();
if(month.equals("February"))
{
continue;
}
else
newstr=newstr+(month+" ");
}
}
pw.print(newstr);
pw.close();
bw.close();
fw.close();
br.close();
fr.close();
}
}
However after running the program, when I open the file, it's all empty. I have just started file handling in java, so I have no clue of what's going on. I would like some help on this problem. Thanks!

You are opening Same file for reading and writing is the issue. Because you are opening file for write immediately after reading and hence it is overwriting the current data.
Just move the Writing code after file reader is closed.
Here is updated code:
public static void main(String []ars)throws IOException
{
FileReader fr=new FileReader("Month.txt");
BufferedReader br=new BufferedReader(fr);
String str;
String newstr="";
while((str=br.readLine())!=null)
{
StringTokenizer S=new StringTokenizer(str);
while(S.hasMoreTokens()==true)
{
String month=S.nextToken();
if(month.equals("February"))
{
continue;
}
else
newstr=newstr+(month+" ");
}
}
br.close();
fr.close();
FileWriter fw=new FileWriter("Month.txt");
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
pw.print(newstr);
pw.close();
bw.close();
fw.close();
}

Here is a much more compact and nicer looking solution:
List<String> lines = Files.readAllLines(Paths.get("Month.txt")); //read every line
//filer out lines that contain february
lines = lines.stream().filer(line -> !line.contains("February")).collect(Collectors.toList());
Files.write(Paths.get("Month.txt"), lines, Charset.defaultCharset()); //write it back
No need to close file reading streams manually, no need to use while loops, and classes like StringTokenizer!

Related

Deleting a record in a file in Java

public class Client {
private Scanner scanner;
private String fileClient="client.txt";
public File client =new File(fileClient);
public void deletClient() {
int lineRemove =GetLineRemove();
String tempFile="temp.txt";
File newfile=new File(tempFile);
int line=0;
String currentLine;
try {
FileWriter fw=new FileWriter(tempFile,true);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
FileReader fr=new FileReader(fileClient);
BufferedReader br=new BufferedReader(fr);
while((currentLine=br.readLine())!=null ) {
line++;
if(line !=lineRemove) {
pw.println(currentLine);
}
}
pw.flush();
fr.close();
bw.close();
pw.close();
br.close();
fw.close();
// i try to delet a file
client.delete();
// create a file have the same name
File dumy=new File(fileClient);
// rename it to first file
newfile.renameTo(dumy);
}catch(Exception e){
System.out.print(e);
}
}
I want to remove a line from a file but when i do that i found the first file still exist and the second file what should get rename to the first file still have has it name temp i don't know should do so i hope u can help me to know where is the problem.

Printed the data from two files in to console , now i want to merge the both data and print in one file using prinWriter

Printed the data from two files in to console , now i want to merge the both data and print in one file using printWriter
for this am using the following code ,
import java.io.*;
class DataM
{
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new FileReader("abc.txt"));
BufferedReader br1=new BufferedReader(new FileReader("def.txt"));
String line=br.readLine();
while(line!=null)
{
System.out.println(line);
line=br.readLine();
}
System.out.println("****************************************************************************");
String line2=br1.readLine();
while(line2!=null)
{
System.out.println(line2);
line2=br1.readLine();
}
//PrintWriter pw=new PrintWriter();
PrintWriter pw=new PrintWriter("ilm.txt");
pw.println(br);
pw.println(br1);
pw.println();
pw.flush();
pw.close();
}
}
I see that you want to print the results of the two files in order, however you have taken the approach:
pw.println(br);
pw.println(br1);
This won't work because those two objects are instances of a Reader. A reader, when called to be a String won't return its contents. So our option here is to store those lines you printed and instead write to the file that way.
So, when you read those two files, let's do this
List<String> lines=new ArrayList<>();
String line=br.readLine();
while(line!=null)
{
System.out.println(line);
lines.add(line);
line=br.readLine();
}
System.out.println("****************************************************************************");
String line2=br1.readLine();
while(line2!=null)
{
System.out.println(line2);
lines.add(line2);
line2=br1.readLine();
}
This will store all those lines so we can write to a file ourselves.
Now to do that...
try(PrintWriter stream=new PrintWriter(new File("ilm.txt"))) {
lines.forEach(stream::println);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
This simply opens a new PrintWriter to write to the file with, similarly to what you have done, where we can write and close the stream automatically.

Editing a text file in java

I want add few strings to a text file in a particular location.
I have used BufferedReader to read the text file. Then I added the string at the particular position and wrote the modified text to a new temp file using BufferedWriter.
Then I deleted the old file and renamed the temp file to old file name.
This works sometimes and does not work sometimes. The delete() function sometimes does not delete the file. I have closed all the BufferedWriter's, but the problem still occurs sometimes.
Code:
public boolean cart(String uname, String item) throws IOException {
File file = new File("C:\\$$$$.tmp");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
File fileop = new File("C:\\value.text");
FileReader fr = new FileReader(fileop.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null) {
String val[] = line.split(",");
if (val[0].equals(uname)) {
String linenew = line + item + "&";
bw.append(linenew);
bw.newLine();
bw.flush();
} else {
bw.append(line);
bw.newLine();
bw.flush();
}
}
br.close();
bw.close();
fileop.delete();
file.renameTo(fileop);
return true;
}
I found the answer by myself after spending one full day of searching..
Answer is:
It is enough to close the bufferedReader but also the fileReader..
fr.close(); should be inserted after br.close();

Modify the content of a file using Java

I want to delete some content of file using java program as below. Is this the write method to replace in the same file or it should be copied to the another file.
But its deleting the all content of the file.
class FileReplace
{
ArrayList<String> lines = new ArrayList<String>();
String line = null;
public void doIt()
{
try
{
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while (line = br.readLine() != null)
{
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
out.write(lines.toString());
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public statc void main(String args[])
{
FileReplace fr = new FileReplace();
fr.doIt();
}
}
I would start with closing reader, and flushing writer:
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
try {
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
The accepted answer is great. However, there is an easier way to replace content in a file using Apache's commons-io library (commons-io-2.4.jar - you can use any latest versions)
private void update() throws IOException{
File file = new File("myPath/myFile.txt");
String fileContext = FileUtils.readFileToString(file);
fileContext = fileContext.replaceAll("_PLACEHOLDER_", "VALUE-TO-BE-REPLACED");
FileUtils.write(file, fileContext);
}
Note: Thrown IOException needs to be caught and handled by the application accordingly.
Read + write to the same file simulatenously is not ok.
EDIT: to rephrase and be more correct and specific - reading and writing to the same file, in the same thread, without properly closing the reader (and flusing the writer) is not ok.
Make sure to:
close any stream when you no longer need them
In particular before reopening it for writing.
truncate the file, to make sure it shrinks if you write less than it had.
then write the output
write individual lines, don't rely on toString.
flush and close when you are finished writing!
If you use buffered IO, you always have to ensure that the buffer is flushed at the end, or you might lose data!
I can see three problems.
First you are writing to out which I assume is System.out, not an output stream to the file.
Second, if you do write to an output stream to the file, you need to close it.
Third, the toString() method on an ArrayList isn't going to write the file like you are expecting. Loop over the list and write each String one at a time. Ask yourself whether you need to write newline characters as well.
The accepted answer is slightly wrong. Here's the correct code.
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
try {
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
}
out.close();
catch (Exception ex) {
ex.printStackTrace();
}
}

Java appending new file's data to old file

In the first step am creating a file say test1.txt and adding records to it, and the rest records to test2.txt. Now i want to append the records of test2.txt to test1.txt. How to append them to test1.txt. The reason am dividing the files is i have a List with about 53K records, which am unable to write in a single file, as the buffer writer is closing as its reaching 52K.
The function am using for creating a single file is
public void exportApprovedList() throws IOException {
File approvedWhiteListFile = new File("/var/tmp/livecron/dictionary.common");
BufferedWriter bw = new BufferedWriter(new FileWriter(approvedWhiteListFile));
if (approvedWhiteListFile.exists()) {
List<WhiteListTerm> approvedWhiteList = whiteListBO.getByStatus("APPROVED");
for (WhiteListTerm whiteList : approvedWhiteList) {
bw.write(whiteList.getTerm() + "|" +
whiteListCategoryBO.getById(whiteList.getCategoryId()).getCategoryname());
bw.newLine();
}
}
bw.close();
}
try this....
import java.io.*;
public class FileReadWrite {
public void writeFile(String sorcefile)
{
try{
FileInputStream fis = new FileInputStream(sorcefile);
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
FileWriter fw=new FileWriter("src/output.java",true);
BufferedWriter bw=new BufferedWriter(fw);
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
System.out.println (strLine);
bw.append(strLine);
}
//Close the input stream
br.close();
dis.close();
fis.close();
fw.flush();
bw.flush();
fw.close();
bw.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String args[])
{
FileReadWrite frw=new FileReadWrite();
frw.writeFile("sorce file name wit hfull path");
}
}

Categories

Resources