I need help with splits and modifying text in Netbeans JAVA

-1

I'm doing a program in JAVA that opens a text file and edits some lines in the file is of this type:

PreUtterance=  
Intensity=100  
Modulation=0  
PBW=333,286,411,525,471.2  
PBS=0  
PBY=0,125.1,-19.3,69.9,  

I need to edit the second and fourth value of the PBW row and multiply it by 2. That is, 286 and 525 multiply them by 2 and leave them like this:

PBW=333,572,411,1050,471.2

I already have how to open the file with an interface and like that but I want to know how to identify the row with "PBW=..." and edit it that way.

    
asked by Skuntank00 18.08.2018 в 06:32
source

1 answer

1

You can work with the method contains () to detect the line you want to modify.

Example of use:

if (linea.contains("PBW=333")){
    ...
}

With split ( ) Trozeas the line by storing it in an array of String

String[] trozos = linea.split(",\s*"); //cogeremos posición 1 y 3

We make the modification of the line in the respective pieces

trozos[1] = String.valueOf(Integer.parseInt(trozos[1]) * 2);
trozos[3] = String.valueOf(Integer.parseInt(trozos[3]) * 2);

We save the line in a String by putting the commas back with everything modified, using the join () and save it in StringBuilder

String str = String.join(",", trozos);
builder.append(str).append("\r\n");

I leave the code to the full ..

public class ModificarArchivo {
    static StringBuilder builder = new StringBuilder();

    public static void main(String[] args) {
        leerFichero();
        escribirEnFichero();
    }

    public static void leerFichero(){
        try (BufferedReader br=new BufferedReader(new FileReader("archivos/fichero1.txt"))) {
            String linea = br.readLine();
            while(linea != null){
                if (linea.contains("PBW=333")){
                    String[] trozos = linea.split(",\s*"); //cogeremos posición 1 y 3

                    trozos[1] = String.valueOf(Integer.parseInt(trozos[1]) * 2);
                    trozos[3] = String.valueOf(Integer.parseInt(trozos[3]) * 2);

                    String str = String.join(",", trozos);

                    builder.append(str).append("\r\n");
                    linea = br.readLine();
                }
                builder.append(linea).append("\r\n");
                linea = br.readLine();
            }

        } catch (FileNotFoundException ex) {
            System.out.println("Archivo no encontrado");
        } catch (IOException ex) {
            System.out.println("Error en el flujo de lectura");
        }
    }

    public static void escribirEnFichero(){
        try(BufferedWriter bw = new BufferedWriter(new FileWriter("archivos/fichero1.txt"))){
            bw.write(builder.toString());
            bw.flush();

        } catch (IOException ex) {
            Logger.getLogger(ModificarArchivo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

And the result of it:

    
answered by 18.08.2018 в 11:48