how to read a txt file with Java

0

I think I also need a BufferedWriter and FileWriter but I do not want to write inside the file I just want to read it, modify what is already read and rest it inside a String

public String substituye(String parrafo) 
{
        StringBuilder content = new StringBuilder();
        File file = Paths.get("desktop/pagina.html").toFile();
        String linea="";

        try(BufferedReader br = new BufferedReader(new FileReader(file)))
        {   
            while(br.ready())
            {   
                linea = br.readLine();
                if(linea.equals("//inicio del parrafo de modificar"))
                    linea = parrafo;
                content.append(linea+"\n");
            }
        }
        catch(IOException io)
        {
            io.printStackTrace();
        }
        return content.toString();
    }

// the problem is that it modifies the file only at the beginning and does not eliminate the rest. That is, it is as if I had deleted the old title of the paragraph and instead of the paragraph in the variable "Paragraph" but the body of the rest of the old paragraph is still there

    
asked by Kevin Velasco 05.05.2017 в 18:39
source

2 answers

0

To read the contents of a file for example a .txt I recommend you use FileReader , example:

File archivo = new File("ruta/del/archivo/a/leer/ejemplo.txt");
FileReader leer = new FileReader(archivo);
int a;

while ((a=leer.read()) != -1) {
    System.out.println((char)a);
}

leer.close()
    
answered by 05.05.2017 / 19:29
source
0

I do not know if I understood you correctly. I would tell you to try the replace instead of the append. Here is the link for the Java StringBuilder class: StringBuilder class

  

replace (int start, int end, String str)   Replaces the characters in a substring of this sequence with characters in the specified String.

    
answered by 05.05.2017 в 19:12