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.