How to search and modify a specific part of a line in a text file

0

I am programming an application that resembles a library. The program will save the author, title, date and subject of a book in a text file, each field separated by commas, in this way:

Don Juan Manuel, Count Lucanor, 1331, novel

The user, of a specific book, can modify both the author, the title, the date and the subject. To do this you must first search for that book, entering its title. My question is this. How do I make my program search, according to the name entered, the file line where it is, and when it does, how to modify any of its fields? I have tried the following. No results:

Path miPath = FileSystems.getDefault().getPath("access.txt");
        ArrayList<String> fileContent = new ArrayList<>(Files.readAllLines(miPath, StandardCharsets.UTF_8));
        String[] miLista = new String[fileContent.size() * 4];
        for (int i = 0; i < fileContent.size(); i++) {
           miLista=fileContent.get(i).split(",");
        }
           //Solo guarda la ultima linea del fichero, mi intencion
           //es guardar en un array todos los elementos separados por
           //, para poder buscarlos recorriendo dicho array 
        Files.write(miPath, fileContent, StandardCharsets.UTF_8);
    
asked by kimbo 15.03.2018 в 16:31
source

1 answer

0

The problem is that the array "myList" is overwriting it in every iteration of the for loop. What you could do is declare an ArrayList and there save the array of strings of each line per element of the arraylist. I put a piece of code that could help you:

Path miPath = FileSystems.getDefault().getPath("access.txt");
    ArrayList<String> fileContent = new ArrayList<>(Files.readAllLines(miPath, StandardCharsets.UTF_8));
    ArrayList<String[]> miArray = new ArrayList<>();
    for (int i = 0; i < fileContent.size(); i++) {
        //aquí añades a cada elemento de miArray el resultado de separar por "," la línea
        miArray.add(fileContent.get(i).split(","));
    }

If the first line is "Don Juan Manuel, Count Lucanor, 1331, novel" in miArray.get (0) you would have the String [] {"Don Juan Manuel", "Count Lucanor", "1331", "novel "} That way you would have the values separated and by lines.

    
answered by 15.03.2018 / 17:47
source