Editing a text file in java - 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();

Related

How can i remove a particular text from a file in java?

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

How to write data to file on starting

I am using below code to write data in a file.
public static void writeDataToFile(final String fileName, final String fileContents) {
try {
File file = new File(Environment.getExternalStorageDirectory() + fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(fileContents);
writer.flush();
writer.close();
} catch (IOException e) {
LogUtility.logInfo(TAG, e.getMessage());
}
}
Here FileWriter Constructor takes boolean that means it concatenates data to file every time to the last data. What I am trying to get is to have a file that has logs of my activities I am performing. And I am achieving via above mentioned code. but the problem is it is always concatenating logs to the last of data every time. What I want is to write new log on starting ever time.By this I will not have search file to the bottom for last log. It will be on start evyer time. Any help
You can set the append flag to false in the FileWriter constructor. Then, use the write() function instead of the append() function
FileWriter writer = new FileWriter(file, false);
writer.write(fileContents);
Why don't you remove the file if it exists:
if (!file.exists()) {
file.createNewFile();
} else {
file.delete()
file.createNewFile();
}
If file does not exist, you have written code to create a new file.
Likewise, if file exists, you can delete the file, and create new one
Before deleting old file, you can copy contents into a String, and add them to content that is to be written in file before writing into file.
StringBuilder contentToWrite = new StringBuilder();
contentToWrite.append(newContent);
if (!file.exists()) {
file.createNewFile();
} else {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = bufferedReader.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line).append("\n");
line = bufferedReader.readLine();
}
contentToWrite.append("\n\n" + sb);
file.delete();
file.createNewFile();
}
FileWriter writer = new FileWriter(file, true);
writer.append(contentToWrite);
writer.flush();
writer.close();
PS: Don't forget to close FileReader and BufferedReader in a finally statement.

Problem to write on txt file on specific line

Student.txt
1,Giannis,Oreos,Man
2,Maria,Karra,Woman
3,Maria,Oaka,Woman
After run my code I take this:
Student.txt
1,Giannis,Oreos,Man
2,Maria,Karra,Woman
3,Maria,Oaka,Woman,2,3,1,3,4,6
But I want, if I search for ID=2 go to 2nd line and put the numbers, like that:
Student.txt
1,Giannis,Oreos,Man
2,Maria,Karra,Woman,2,3,1,3,4,6
3,Maria,Oaka,Woman
Code:
#FXML
TextField ID1,glossa,math,fis,xim,prog,gym;
#FXML
public void UseAddLesson() throws IOException{
Scanner x = new Scanner("src/inware/students.txt");
FileWriter fW = new FileWriter("src/inware/students.txt",true);
BufferedWriter bW = new BufferedWriter(fW);
boolean found= false;
while(!found){
String line = x.nextLine();
if(line.contains(ID1.getText())){
bW.write(","+glossa.getText()+",");
bW.write(math.getText()+",");
bW.write(fis.getText()+",");
bW.write(xim.getText()+",");
bW.write(prog.getText()+",");
bW.write(gym.getText());
System.out.println(line);
found= true;
}
}
bW.close();
fW.close();
x.close();
}
Do not attempt to read/write to the same file at the same time. You also cannot append/overwrite the structure of a text file requires all the text following the inserting point to be written at a different position.
I recommend creating a temporary file and replacing the old file with the new one you're done:
#FXML
public void UseAddLesson() throws IOException{
String searchText = ID1.getText();
Path p = Paths.get("src", "inware", "students.txt");
Path tempFile = Files.createTempFile(p.getParent(), "studentsTemp", ".txt");
try (BufferedReader reader = Files.newBufferedReader(p);
BufferedWriter writer = Files.newBufferedWriter(tempFile)) {
String line;
// copy everything until the id is found
while ((line = reader.readLine()) != null) {
writer.write(line);
if (line.contains(searchText)) {
writer.write(","+glossa.getText()+",");
writer.write(math.getText()+",");
writer.write(fis.getText()+",");
writer.write(xim.getText()+",");
writer.write(prog.getText()+",");
writer.write(gym.getText());
break;
}
writer.newLine();
}
// copy remaining lines
if (line != null) {
writer.newLine();
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
}
}
// copy new file & delete temporary file
Files.copy(tempFile, p, StandardCopyOption.REPLACE_EXISTING);
Files.delete(tempFile);
}
Note: If you distribute the app, probably the src directory will become unavailable.

Adding data to files [duplicate]

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

Not entering while loop

I'm trying to write in a file whatever the user has written.
The file creates and all but the program fails to write whatever the user wrote from the program, to the file (The program is like notepad). It wont enter the while loop because the String line is null even if I write something in my program.
It seems it's returning null when I print the "line" String after using br.readLine().
while ((line = br.readLine()) != null) {
bw.write(line);
textArea.append("it worked");
}
Full code:
try {
path = fileChooser.getSelectedFile().getAbsolutePath().replace('\\', '/')
+ "/";
File file = new File(path + File.separator +
JOptionPane.showInputDialog(null, "File name", "File") + ".txt");
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
textArea.append("it worked");
}
bw.flush();
bw.close();
textArea.append(path);
} catch(IOException e1) {
e1.printStackTrace();
}
file.createNewFile();
. . .
BufferedReader br = new BufferedReader(new FileReader(file));
The reader works from an empty file that just has been created. Of course br.readLine() will return null immediately since the file is empty.
Instead of the while loop, I would simply write:
bw.write(textArea.getText());

Categories

Resources