web-dev-qa-db-fra.com

Quelle est la manière la plus simple d'écrire un fichier texte en java

Bonjour, je me demande quelle est la façon la plus simple (et la plus simple) d'écrire un fichier texte en Java. Soyez simple, car je suis un débutant: D J'ai cherché sur le Web et trouvé ce code, mais j'en comprends 50%.

import Java.io.BufferedWriter;
import Java.io.File;
import Java.io.FileWriter;
import Java.io.IOException;

public class WriteToFileExample {
public static void main(String[] args) {
    try {

        String content = "This is the content to write into file";

        File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

33

Avec Java 7 et plus, un liner utilisant Files :

String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
76
dazito

Vous pouvez le faire en utilisant Java 7 Nouveau File API.

exemple de code: `

public class FileWriter7 {
    public static void main(String[] args) throws IOException {
        List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
        String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
        writeSmallTextFile(lines, filepath);
    }

    private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
        Path path = Paths.get(aFileName);
        Files.write(path, aLines, StandardCharsets.UTF_8);
    }
}

"

19
Dilip Kumar

Vous pouvez utiliser FileUtils d'Apache Commons:

import org.Apache.commons.io.FileUtils;

final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);
15
Jakub H

Ajout du fichier FileWriter (String fileName, boolean append)

try {   // this is for monitoring runtime Exception within the block 

        String content = "This is the content to write into file"; // content to write into the file

        File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here

        // if file doesnt exists, then create it
        if (!file.exists()) {   // checks whether the file is Exist or not
            file.createNewFile();   // here if file not exist new file created 
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
        BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
        bw.write(content); // write method is used to write the given content into the file
        bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect. 

        System.out.println("Done");

    } catch (IOException e) { // if any exception occurs it will catch
        e.printStackTrace();
    }
7
newuser

Files.write () la solution simple comme l'a dit @Dilip Kumar. J'ai utilisé de cette façon jusqu'à ce que je rencontre un problème, ne peut pas affecter le séparateur de ligne (Unix/Windows) CR LF.

Alors maintenant j'utilise un Java 8 façon d'écriture de fichier de flux, ce qui me permet de manipuler le contenu à la volée. :)

List<String> lines = Arrays.asList(new String[] { "line1", "line2" });

Path path = Paths.get(fullFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {   
    writer.write(lines.stream()
                      .reduce((sum,currLine) ->  sum + "\n"  + currLine)
                      .get());
}     

De cette façon, je peux spécifier le séparateur de ligne ou je peux faire n'importe quel type de magie comme TRIM, majuscule, filtrage, etc.

4
Laszlo Lugosi

Votre code est le plus simple. Mais j'essaie toujours d'optimiser davantage le code. Voici un exemple.

try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
    bw.write("Hello, This is a test message");
    bw.close();
    }catch (FileNotFoundException ex) {
    System.out.println(ex.toString());
    }
4
Kumaran Ramanujam
String content = "your content here";
Path path = Paths.get("/data/output.txt");
if(!Files.exists(path)){
    Files.createFile(path);
}
BufferedWriter writer = Files.newBufferedWriter(path);
writer.write(content);
3
laughing buddha