Good day.

Tell me please. I use the following methods to write information to a file and read from it:

public static void PrintToFile(String ManufacturerFilePath, String NewManufacturer) { File file = new File(ManufacturerFilePath); FileWriter writer = null; try { writer = new FileWriter(file, true); writer.write(NewManufacturer); writer.write("\r\n"); } catch (IOException e) { e.printStackTrace(); } finally { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } //Чтение из файла. public static void ReadFromFile() { try (FileReader reader = new FileReader("D:\\Warehouse\\ManufacturerList.txt")) { int readIt; while ((readIt = reader.read()) != -1) { System.out.print((char) readIt); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } 

The txt records information in the following form:

Manufacturer1

Manufacturer2

Manufacturer3

I want to use the method that will remove the manufacturer from the file (without overwriting the new file) based on the manufacturer's name entered by the user. Those. user enter "Manufacturer2" - delete it from txt file. I get a file with the content as a result:

Manufacturer1

Manufacturer3

It seems to understand how to delete lines from a file, but for this you need:

  1. Compare the manufacturer that the user entered with what is in the file.

  2. If matched, find the string.

  3. Delete row.

But is it possible to make it easier? Those. find in the file the word that matches the user entered and delete it?

PS This is completely new, so I will be especially grateful for simple solutions :)

Message to bypass editing restrictions.

    1 answer 1

    I dare to assume that the file is an external structure for your application. Therefore, one way or another, it needs to be read into an array of bytes, either line by line or in some other way. Next, determine the occurrence of the first and last byte (string) and remove bytes from the array (array of strings). And you have to write back (although not to another file, but still put the full content back into the file).

    • RandomAccesFile allows you to find the bytes of the desired fishing, and immediately replace them. But deleting will result in the next byte array being shifted. - Avbat