2010-04-12 12 views

उत्तर

13

कैसे इस बारे में:

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:

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

फ़ाइल को लिखने के लिए खोलें, और इसे सहेजें। यह फ़ाइल की सामग्री को हटा देता है।

+8

आपका मतलब है, "लिखने के लिए फ़ाइल को खोलने, और यह _close_" करने के लिए फ़ाइल की लंबाई सेट होगा? –

1

आप फ़ाइल for writing and then truncating its content खोलकर करते हैं सकता है, निम्न उदाहरण NIO का उपयोग करता है अभी पिछले 20 फ़ाइल के बाइट्स काटना:

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

हाय, उत्तर के लिए धन्यवाद। क्या फ़ाइल सामग्री को आंशिक रूप से हटाने का कोई तरीका है जिसका मतलब है ऑफसेट से शुरू करना और हटाना गिनना? –

1

समस्या हो सकती है क्या यह केवल सिर को छोड़ देता है जो मुझे लगता है और पूंछ नहीं?

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) 
    { 

    } 

इस कोड 'फाइल' की वर्तमान सामग्री को हटा दें और 0.

संबंधित मुद्दे