Hi my problem is that I have a text with something like :
something1
[ something2
something3
[ something4
I want to write a code in java that reads that text and search for a character, in this case "[", when it finds it, remove the entire line, in this case "[ something2" , and then keep searching for that character so in the end I will be having something like this
something1
something3
I already search for something like this and I find this approach
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "bbb";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine);
}
boolean successful = tempFile.renameTo(inputFile);
That code removes the entire line that haves in it "bbb", the problem here is that erases only the line that has in it only and elusively bbb
by example
something1
bbb
something3
bbb something
after run the code we have
something1
something3
bbb something
so I tried to modify the code to search for the character [ and then erases the entire line.
but I couldn't, so I was hopping that someone could help me.
Try this:
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "bbb";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(!trimmedLine.contains(lineToRemove))
{
writer.write(currentLine);
}
}
boolean successful = tempFile.renameTo(inputFile);
that code removes the entire line that haves in it "bbb", the problem here is that erases only the line that has in it only and elusively bbb by example
COZ of if(trimmedLine.equals(lineToRemove)) continue;
"bbb something".equals("bbb") returns false and so the line is not skipped
Use regex or String.startsWith() or String.contains() method
Try the following:
if(trimmedLine.contains(lineToRemove)) continue;
[EDIT]
What I recommend is to implement KMP [1] in java (Pattern Matching). Will help you in future.
[1] http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
You don't need to write a Java program for this. Chances are you have an OS that knows tools like grep, awk, perl. For example
grep -v '^\[' infile >outfile
will copy the lines you want from file infile to outfile
You should use the contains method.
while((currentLine = reader.readLine()) != null) {
// CHANGED EQUALS TO CONTAINS
if(trimmedLine.contains(lineToRemove)) continue;
writer.write(currentLine);
}
Good luck!
Related
I am trying to read multiple lines from a file into an ArrayList as a String.
What I aim to do is to make it so the program reads from a file line by line until the reader sees a specific symbol (- in this case) and saves those rows as one single String. the code below makes every row a new string that it later adds to the list instead.
BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
String read;
while ((read = br.readLine()) != null) {
String[] splited = read.split("-");
carList.add(Arrays.toString(splited));
}
for (String carList2 : carList) {
System.out.println(carList2);
System.out.println("x");
}
First, you need to check if the read line contains "-".
If it doesn't, concatenate the line with the previous ones.
If it does, concatenate only the first part of the line with the previous line.
This is a quick implementation:
BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
String read;
String concatenatedLine = "";
while ((read = br.readLine()) != null) {
String[] splited = read.split("-");
// if line doesn't contains "-", splited[0] and read are equals
concatenatedLine += splited[0];
if (splited.length > 1) {
// if read line contains "-", there will be more than 1 element
carList.add(Arrays.toString(splited)); // add to the list
// store the second part of the line, in order to add it to the next ones
concatenatedLine = splited[1];
}
}
Note the output could not be what is expected if a line contains more than one -.
Also, concatenating String using + is not the best way to do it, but I let you find out more about that.
It's not very clear for me what is the output you desire.
If you would like to have each customer on one string without "-"
then you could try the following code:
while ((read = br.readLine()) != null) {
String splited = read.replace("-", " ");
carList.add(splited);
}
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();
}
}
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
How can I remove or trim a line in a text file in Java?
This is my program but it does not work.
I want to remove a line in text file, a line contain the word of user input
try {
File inputFile = new File("temp.txt");
File tempFile = new File("temp1.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = name;
String currentLine;
while((currentLine = reader.readLine()) != null)
{
//trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(!trimmedLine.startsWith(lineToRemove))
{
// if current line not start with lineToRemove then write to file
writer.write(currentLine);
}
}
writer.close();
reader.close();
}
catch(IOException ex)
{
System.out.println("Error reading to file '" + fileName + "'");
}
You are not separating the lines with a line break character, so the resulting file will have one single long line. One possible way to fix that is just writing the line separator after each line.
Another possible problem is that you are only checking if the current line starts with the given string. If you want to check if the line contains the string you should use the contains method.
A third problem is that you are not writing the trimmed line, but the line as it is. You really don't say what you expect from the program, but if you are supposed to output trimmed lines it should look like this:
if(!trimmedLine.contains(lineToRemove)) {
writer.write(trimmedLine);
writer.newLine();
}
startsWith() is the culprit. You are checking if the line starts with "lineToRemove". As #Joni suggested use contains.
I'm having a hard time deleting a row of lines in a text file, I've use this code but i end up deleting all the lines instead, need some help.
try //vacation leave/
{
File inputFile = new File("Adlawan" + code1);
File tempFile = new File("AdalwanTempFile");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "AdlawanJan2012";
String currentLine;
while((currentLine = reader.readLine()) != null)
{
//trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove))
{
writer.write(currentLine);
}
}
writer.close();
reader.close();
if(!inputFile.delete())
{
JOptionPane.showMessageDialog(null, "Could not rename file");
return;
}
if(!tempFile.renameTo(inputFile))
JOptionPane.showMessageDialog(null, "Could not rename file");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, " ");
}
The data on the file looks like this:
AdlawanJan2012 Vacation-Leave-Credits -0.6875
AdlawanFeb2012 Vacation-Leave-Credits -0.6875
AdlawanMar2012 Vacation-Leave-Credits -0.6875
Desired result after trimming the lines:
AdlawanFeb2012 Vacation-Leave-Credits -0.6875
AdlawanMar2012 Vacation-Leave-Credits -0.6875
Thank you...
I think you're trying to delete line in a file if the line starts with the "lineToRemove" variable, in that case you might want to use "startsWith" method instead of "equal" method.
while((currentLine = reader.readLine()) != null)
{
//trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(!trimmedLine.startsWith(lineToRemove))
{
// if current line not start with lineToRemove then write to file
writer.write(currentLine);
}
}
trim() method only removes leading and trailing white spaces and not characters after white space.
String lineToRemove = "AdlawanJan2012";
....
String trimmedLine = currentLine.trim();
if(trimmedLine.substring(0, 14).equals(lineToRemove)) {
//Your deletion logic
}
It'a a good idea to read the file content line by line and copy them to another file(temporal file) preferably a Random Access file and omit the line you want to remove. just copy the rest to the temporal file and omit the line(s) you want to delete. then rename the file to original name. No samples Please. I need you to do this on your own that way you'll learn all by your self. good luck