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.
Related
Im trying to delete the original file ("order2.txt") and rename the temp file to ("order2.txt") that I have store the new data. But for some reason the original could not be delete and it also cant rename the temp file. Anyone know what is wrong with my code and how can i fix it??
void editRecord(String editTerm){
String tempFile="temp.txt";
String file="order2.txt";
File oldFile=new File(file);
File newFile=new File(tempFile);
String ID1="";
String status1="";
String food1="";
String fq1="";
String d1="";
String dq1="";
System.out.println("l");
try{
System.out.println("2");
FileWriter fw=new FileWriter(tempFile,true);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
Scanner x=new Scanner(new File(file));
x.useDelimiter("[,\n]");
System.out.println("3");
while(x.hasNext()){
ID1=x.next();
status1=x.next();
food1=x.next();
fq1=x.next();
d1=x.next();
dq1=x.next();
System.out.println(dq1);
String newStatus =statusTextField.getText();
if(ID1.equals(editTerm))
{
System.out.println(status1);
pw.println(ID1+","+newStatus+","+food1+","+fq1+","+d1+","+dq1);
System.out.println(ID1+","+newStatus+","+food1+","+fq1+","+d1+","+dq1);
}
else
{
System.out.println(ID1+","+status1+","+food1+","+fq1+","+d1+","+dq1);
pw.println(ID1+","+status1+","+food1+","+fq1+","+d1+","+dq1);
System.out.println("y");
}
System.out.println("t");
}
x.close();
pw.flush();
pw.close();
System.out.println("t");
oldFile.delete();
File dump = new File(file);
newFile.renameTo(dump);
System.out.println("f");
}
catch(IOException ex) {
System.out.println("fail");
}
}
I have tried to implement a simple program to delete a particular text from a file, some how it is not able to delete it. I am reading entire file content into a temp file , delete the user input string from it and update the content to the original file.
Any help would be highly appreciated.
public class TextEraser{
public static void main(String[] args) throws IOException {
System.out.print("Enter a string to remove : ");
Scanner scanner = new Scanner(System. in);
String inputString = scanner. nextLine();
// Locate the file
File file = new File("/Users/lobsang/documents/input.txt");
//create temporary file
File temp = File.createTempFile("file", ".txt", file.getParentFile());
String charset = "UTF-8";
try {
// Create a buffered reader
// to read each line from a file.
BufferedReader in = new BufferedReader(new FileReader(file));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
String s = in.readLine();
// Read each line from the file and echo it to the screen.
while (s !=null) {
s=s.replace(inputString,"");
s = in.readLine();
}
writer.println(s);
// Close the buffered reader
in.close();
writer.close();
file.delete();
temp.renameTo(file);
} catch (FileNotFoundException e1) {
// If this file does not exist
System.err.println("File not found: " + file);
}
}
After replace with input string, write string immediate in file.
while (s != null) {
s = s.replace(inputString, "");
writer.write(s);
// writer.newLine();
s = in.readLine();
}
For new line , use BufferedWriter in place of PrintWriter, it contains method newLine()
writer.newLine();
Remove this
writer.println(s);
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!
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 6 years ago.
private void AddAccount(String usernamenew, String passwordnew) {
final String FileName = "F:/TextFiles/loginaccs.txt";
File file = new File(FileName);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(usernamenew);
bw.newLine();
bw.write(passwordnew);
bw.newLine();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, I tried to write two extra lines to a text file, which is a new username and a new password.
After deleting some of the lines, the program deletes everything in the text file and write two lines, which is not what I wanted.
Am I doing something wrong? Thanks in Advance.
After you write to the BufferedWriter, for the file, you then close it, which is fine.
However, you then create another FileOutputStream. In addition, you should not have a reader and writer of the same file at the same time. All you need to do is create the BufferedWriter, write the file and close it.
private void AddAccount(String usernamenew, String passwordnew) {
final String FileName = "F:/TextFiles/loginaccs.txt";
File file = new File(FileName);
try {
// BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(usernamenew);
bw.newLine();
bw.write(passwordnew);
bw.newLine();
bw.close();
// FileOutputStream fos = new FileOutputStream(file);
// fos.close();
// br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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");
}
}