Answer the question
In order to leave comments, you need to log in
How to remove a specific line from a file?
It is necessary to remove a certain line from the file. I did it like this, but it doesn't work:
public static void deleteServer(int index) {
StringBuilder builder = new StringBuilder();
try
{
File file = new File(getFilePath());
BufferedReader reader = new BufferedReader(new FileReader(file));
int current = 0;
String line;
while ((line = reader.readLine()) != null) {
if (current != index)
builder.append(line);
current++;
}
FileWriter writer = new FileWriter(file);
writer.write(builder.toString());
writer.close();
reader.close();
}
catch (IOException e)
{
}
}
Answer the question
In order to leave comments, you need to log in
public static void deleteServer(int index) throws IOException {
BufferedReader reader = null;
PrintWriter writer = null;
try {
File file = new File(getFilePath());
String fileToWrite = "fileToWrite.txt";
reader = new BufferedReader(new FileReader(file));
writer = new PrintWriter(new FileWriter(fileToWrite));
int current = 0;
String line;
while ((line = reader.readLine()) != null) {
if (current != index) {
writer.println(line);
}
current++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
if (reader != null) {
reader.close();
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question