2010-04-12 83 views

Respuesta

13

¿Qué tal esto:

new RandomAccessFile(fileName).setLength(0); 
1

Abra el archivo para escribir y guárdelo. Borra el contenido del archivo.

+8

quiso decir, "abrir el archivo para escritura, y que _close_"? –

1

Se podría hacer esto abriendo el archivo for writing and then truncating its content, el siguiente ejemplo utiliza NIO:

import static java.nio.file.StandardOpenOption.*; 

Path file = ...; 

OutputStream out = null; 
try { 
    out = new BufferedOutputStream(file.newOutputStream(TRUNCATE_EXISTING)); 
} catch (IOException x) { 
    System.err.println(x); 
} finally { 
    if (out != null) { 
     out.flush(); 
     out.close(); 
    } 
} 

Another way: truncar sólo en los últimos 20 bytes del archivo:

import java.io.RandomAccessFile; 


RandomAccessFile file = null; 
try { 
    file = new RandomAccessFile ("filename.ext","rw"); 
    // truncate 20 last bytes of filename.ext 
    file.setLength(file.length()-20); 
} catch (IOException x) { 
    System.err.println(x); 
} finally { 
    if (file != null) file.close(); 
} 
+0

hola, gracias por la respuesta. ¿Hay alguna manera de eliminar parcialmente el contenido del archivo significa partir de un desplazamiento particular y contar para eliminar? –

3
new FileOutputStream(file, false).close(); 
1

¿El problema de mayo es que esto deja solo la cabeza y no la cola?

public static void truncateLogFile(String logFile) { 
    FileChannel outChan = null; 
    try { 
     outChan = new FileOutputStream(logFile, true).getChannel(); 
    } 
    catch (FileNotFoundException e) { 
     e.printStackTrace(); 
     System.out.println("Warning Logfile Not Found: " + logFile); 
    } 

    try { 
     outChan.truncate(50); 
     outChan.close(); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
     System.out.println("Warning Logfile IO Exception: " + logFile); 
    } 
} 
0
try { 
     PrintWriter writer = new PrintWriter(file); 
     writer.print(""); 
     writer.flush(); 
     writer.close(); 

    }catch (Exception e) 
    { 

    } 

Este código se eliminará el contenido actual del 'archivo' y establecer la longitud del archivo a 0.

Cuestiones relacionadas