package javaapplication3;
import java.io.*;
public class LeeEscribeArchivo {
/**
* Busca todo el contenido entero de un texto y lo regresa en un Strin.
*/
static public String obtieneContenidoArchivo(File archivoAbierto) {
StringBuilder contenido = new StringBuilder();
try {
BufferedReader entrada = new BufferedReader(new FileReader(archivoAbierto));
try {
String line = null;
while (( line = entrada.readLine()) != null){
contenido.append(line);
contenido.append(System.getProperty("line.separator"));
}
}
finally {
entrada.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contenido.toString();
}
/**
* Cambia el contenido de un archivo de testo en su totalidad.. sobreescribiendo
* el texto existente
**/
static public void agregaContenidoArchivo(File archivoAbierto, String contenido)
throws FileNotFoundException, IOException {
if (archivoAbierto == null) {
throw new IllegalArgumentException("El archivo no debe ser nulo.");
}
if (!archivoAbierto.exists()) {
throw new FileNotFoundException ("el archivo no existe: " + archivoAbierto);
}
if (!archivoAbierto.isFile()) {
throw new IllegalArgumentException("no debe ser un directorio: " + archivoAbierto);
}
if (!archivoAbierto.canWrite()) {
throw new IllegalArgumentException("El archivo no puede ser escrito: " + archivoAbierto);
}
Writer output = new BufferedWriter(new FileWriter(archivoAbierto));
try {
output.write( contenido );
}
finally {
output.close();
}
}
public static void main (String... aArguments) throws IOException {
File archivoPrueba = new File("C:\\hola.txt");
System.out.println("Contenido original: " + obtieneContenidoArchivo(archivoPrueba));
agregaContenidoArchivo(archivoPrueba, "El contenido ha sido sobreescribido...");
System.out.println("Nuevo contenido: " + obtieneContenidoArchivo(archivoPrueba));
}
}
Advertisement