How to delete a line from text line by id java - 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();
}
}

Related

How to split single text file into multiple with character as delimiter

I have a text document that has multiple separate entries all compiled into one .log file.
The format of the file looks something like this.
$#UserID#$
Date
User
UserInfo
SteamFriendID
=========================
<p>Message</p>
$#UserID#$
Date
User
UserInfo
SteamFriendID
========================
<p>Message</p>
$#UserID#$
Date
User
UserInfo
SteamFriendID
========================
<p>Message</p>
I'm trying to take everything in between the instances of "$#UserID$#", and print them into separate text files.
So far, with the looking that I've done, I tried implementing it using StringBuilder in something like this.
FileReader fr = new FileReader(“Path to raw file.”);
int idCount = 1;
FileWriter fw = new FileWriter("Path to parsed files" + idCount);
BufferedReader br = new BufferedReader(fr);
//String line, date, user, userInfo, steamID;
StringBuilder sb = new StringBuilder();
//br.readLine();
while ((line = br.readLine()) != null) {
if(line.substring(0,1).contains("$#")) {
if (sb.length() != 0) {
File file = new File("Path to parsed logs" + idCount);
PrintWriter pw = new PrintWriter(file, "UTF-8");
pw.println(sb.toString());
pw.close();
//System.out.println(sb.toString());
Sb.delete(0, sb.length());
idCount++;
}
continue;
}
sb.append(line + "\r\n");
}
But this only gives me the first 2 of the entries in separate parsed files. Leaving the 3rd one out for some reason.
The other way I was thinking about doing it was reading in all the lines using .readAllLines(), store the list as an array, loop through the lines to find "$#", get that line's index & then recursively write the lines starting at the index given.
Does anyone know of a better way to do this, or would be willing to explain to me why I'm only getting two of the three entries parsed?
Short / quick fix is to write the contents of the StringBuilder once after your while loop like this:
public static void main(String[] args) {
try {
int idCount = 1;
FileReader fr = new FileReader("<path to desired file>");
BufferedReader br = new BufferedReader(fr);
//String line, date, user, userInfo, steamID;
StringBuilder sb = new StringBuilder();
//br.readLine();
String line = "";
while ((line = br.readLine()) != null) {
if(line.startsWith("$#")) {
if (sb.length() != 0) {
writeFile(sb.toString(), idCount);
System.out.println(sb);
sb.setLength(0);
idCount++;
}
continue;
}
sb.append(line + "\r\n");
}
if (sb.length() != 0) {
writeFile(sb.toString(), idCount);
System.out.println(sb);
idCount++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeFile(String content, int id) throws IOException
{
File file = new File("<path to desired dir>\\ID_" + id + ".txt");
file.createNewFile();
PrintWriter pw = new PrintWriter(file, "UTF-8");
pw.println(content);
pw.close();
}
I've changed two additional things:
the condition "line.substring(0,1).contains("$#")" did not work properly, the substring call only returns one character, but is compared to two characters -> never true. I changed that to use the 'startsWith' method.
After the content of the StringBuilder is written to file, you did not reset or empty it, resulting in the second and third file containing every previous blocks aswell (thrid file equals input then...). So thats done with "sb.setLength(0);".

How to update a string with new value in java?

I am new to java and working on file operations. I have this input and modify text files as follows:
input.txt: contains id,firstname,lastname
1000:Mark,Peters,3.9
modify.txt: contains id,oldvalue:newvalue
1000,Mark:John
I am supposed to search the id and make the updations accordingly. So in modify.txt file I have an id and old value which is to be replaced with new value in the input.txt
So after modification, my input.txt line output should be printed as:
1000:John,Peters,3.9
I have written the following code, but I am not sure how to proceed with updations. However, I have managed to read the files and split it and get the id.
public static void main(String[] args) {
try {
BufferedReader file1 = new BufferedReader(new FileReader(new File("src/input.txt")));
BufferedReader file2 = new BufferedReader(new FileReader(new File("src/modify.txt")));
String str1 = file1.readLine();
String input[] = str1.split(":");
int id1 = Integer.parseInt(input[0]);
System.out.println(str1);
System.out.println(id1);
String str2 = file2.readLine();
String modify[] = str2.split(",");
int id2 = Integer.parseInt(modify[0]);
System.out.println(str2);
System.out.println(id2);
file1.close();
file2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Can anyone help me with this? Thanks. Appreciate your help.
You can read the line in modify.txt file and split the line using regex [,:]. It will split the line into separate parts like id, firstName and lastName etc.
After read the each line in input.txt file and and split the each line using the regex [,:]. And compare the first element in the list with element in the list created from modify.txt file. if the element is equals replace the line with the new data from list created from modify.txt file.
public static void main(String[] args) {
try {
BufferedReader f1 = new BufferedReader(new FileReader(new File("src/input.txt")));
BufferedReader f2 = new BufferedReader(new FileReader(new File("src/modify.txt")));
String regex = "[,:]";
StringBuffer inputBuffer = new StringBuffer();
String line;
String[] newLine = f2.readLine().split(regex);
while ((line = f1.readLine()) != null) {
String[] data = line.split(regex);
if (data[0].equals(newLine[0])) {
line = line.replace(newLine[1], newLine[2]);
}
inputBuffer.append(line);
inputBuffer.append(System.lineSeparator());
}
f1.close();
f2.close();
FileOutputStream fileOut = new FileOutputStream("src/input.txt");
fileOut.write(inputBuffer.toString().getBytes());
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}

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

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.

How to edit parts of a line in a text file in java

I'm trying to delete the last four characters of all the lines in a text file. Let's say I have domain.txt and the content:
123.com
student.com
tech.net
running into hundreds of lines. How do I delete the last four characters (the extensions) to remain:
123
student
tech
etc.
I hope this helps.
UPDATED
String a ="123.com";
System.out.println(a.substring(0, a.lastIndexOf(".")));
You can do as below :
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "",
newtext = "";
while((line = reader.readLine()) != null) {
line=line.substring(0, line.lastIndexOf("."))
newtext += line + "\n";
}
reader.close();
// Now write new Content
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);
writer.close();
Do not forget to use try..catch

Inserting a big text file into netbeans

try {
BufferedReader br = new BufferedReader(new FileReader("Help.txt"));
String helptext = br.readLine();
helpText.setText(helptext);
} catch (IOException e) {
System.out.println ("Error: " + e);
}
It only returns the first line of the text file and the text file is about 4 pages long.
"helptext" being a text area.I want the whole file with its spaces I made in the text area.
This will give only 1 line where in your file the first line whatever contain to get all the line you need get into the loop
StringBuffer sb = new StringBuffer();
String line = null;
while((line=br.readLine()) !=null){
sb.append(line);
}
helpText.setText(sb.toString());
You need to loop through the text file. You are only telling it to readline() one time.
EDIT: Fixed code to be exactly what user needed
EDIT 2: Added code to keep cursor at top
String line;
try {
BufferedReader br = new BufferedReader(new FileReader("<Location of text file>"));
while((line=br.readLine()) != null){
helpText.append(line);
//Add a new line for the next entry (If you would like)
helpText.append("\n");
}
//Set Cursor back to start
helpText.setCaretPosition(WIDTH);
}
catch (IOException e) {
System.out.println (e);
}
you have to read every line in a loop.
String line = br.readLine();
String helptext = "";
while(line != null) {
helptext = helptext + line;
line = br.readLine();
}
helpText.setText(helptext);

Categories