2012-07-17 7 views

risposta

4

è semplicemente un file di testo che denota line endings con \n invece di \n\r (Windows) o \r (Mac OSX prima).

Ecco l'idea di base; scrivere ogni riga, seguito da un esplicito \n (piuttosto che .newLine() che è dipendente dalla piattaforma):

public static void writeText(String[] text){ 
    Path file = Paths.get("/tmp/filename"); 
    try (BufferedWriter bw = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { 
    for(String s : text){ 
     bw.write(s); 
     bw.write("\n"); 
    } 
    } catch (IOException e) { 
    System.err.println("Failed to write to "+file); 
    } 
} 
+3

Invece di usare '\ n' o' \ r \ n', usa 'System.getProperty (" line.separator ")'. –

+0

Grazie a dimo414 e Eng.Fouad. L'esempio sopra ha aiutato molto. – Piyush

+2

@ Eng.Fouad In generale, vero, ma se vuoi un file in formato Unix indipendentemente dal sistema operativo in cui ti trovi, ti consigliamo di usare '\ n' esplicitamente. Ottenere il separatore di riga del sistema significa che otterrai un comportamento diverso a seconda del sistema operativo su cui esegui il programma. – dimo414

Problemi correlati