I want to have a method that will take the file path and then delete a specific line from a text file and this is the code I came up with.
Method.java
public class Method {
static void deletefileline(String file, Integer line) throws IOException {
ArrayList<String> filecontent = new ArrayList<String>();
try {
File myObj = new File(file);
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
filecontent.add(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
File f = new File(file);
f.delete();
filecontent.remove(line);
try {
File newfile = new File(file);
newfile.createNewFile();
} catch (IOException e) {
System.out.println("An Error Occured");
}
for (Integer i = 0; i < filecontent.size(); i ) {
String textToAppend = "\r\n" filecontent.get(i);
Path path = Paths.get(file);
Files.write(path, textToAppend.getBytes(), StandardOpenOption.APPEND);
}
}
public static void main(String[] args) {
deletefileline("src/test.txt", 1);
}
}
This is the text file
test.txt
hi
hello
hii
helloo
This is the text file after i ran Methods.java
Output:
hi
hello
hii
helloo
It won't show it but at the first "hi" before that there is a space so it only added a space at line 1.
So the problem is that when it is running it only adds an extra line at line 1.
CodePudding user response:
Why is not the line removed?
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
E remove(int index)
Removes the element at the specified position in this list.boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present.
Since Integer line
is Object
and not a primitive data type int
, this call
filecontent.remove(line);
tries to remove the line with a content equal to new Integer(1)
.
Change the method argument to int line
or add type cast to the call filecontent.remove((int) line)
.
Why is an empty line added?
The extra space is added by this statement:
String textToAppend = "\r\n" filecontent.get(i);
Change it like this:
String textToAppend = filecontent.get(i) "\r\n";
CodePudding user response:
This is a small snippet to perform same function as mentioned in question (kotlin version, however same can be done in java)
import java.io.File
class RemoveFileContent {
fun deleteContentAtIndex(filePath: String, indexPos: Int) {
val bufferedWriter = File("/SampleOutputFile.txt").bufferedWriter()
File(filePath).readLines().filterIndexed { i, _ -> i != indexPos }.forEach {
bufferedWriter.appendLine(it)
}
bufferedWriter.flush()
}
}
fun main(args : Array<String>) {
RemoveFileContent().deleteContentAtIndex("/SampleFile.txt",2)
}
Input : Output:
hi hi
hello hello
hii helloo
helloo
Disclaimer : Note that if your file content are huge, this can lead to high memory consumption, as stated here - How to remove first line of a text file in java