在java中编写文本文件的最简单方法是什么?

时间:2014-04-04 09:55:47

标签: java file text

您好,我想知道在java中编写文本文件最简单(也是最简单)的方法是什么。请简单,因为我是初学者:D 我在网上搜索并找到了这段代码,但我理解了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();
    }
}

}

9 个答案:

答案 0 :(得分:73)

使用Java 7及更高版本,使用Files

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

答案 1 :(得分:18)

您可以使用JAVA 7File API

来完成此操作

代码示例: `

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);
    }
}

`

答案 2 :(得分:14)

您可以使用Apache Commons的FileUtils

import org.apache.commons.io.FileUtils;

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

答案 3 :(得分:7)

追加文件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();
    }

答案 4 :(得分:4)

您的代码最简单。但是,我总是试图进一步优化代码。这是一个样本。

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());
    }

答案 5 :(得分:4)

Files.write()简单的解决方案正如@Dilip Kumar所说。我曾经使用那种方式,直到我面临一个问题,不能影响行分隔符(Unix / Windows)CR LF。

所以现在我使用Java 8流文件编写方式,允许我动态操作内容。 :)

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());
}     

通过这种方式,我可以指定行分隔符,或者我可以做任何类型的魔术,如TRIM,大写,过滤等。

答案 6 :(得分:3)

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

答案 7 :(得分:0)

Java 11或更高版本中,可以从writeString开始使用java.nio.file.Files

String content = "This is my content";
String fileName = "myFile.txt";
Files.writeString(Paths.get(fileName), content); 

带有选项:

Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)

有关java.nio.file.FilesStandardOpenOption的更多文档

答案 8 :(得分:-2)

File file = new File("path/file.name");
IOUtils.write("content", new FileOutputStream(file));

IOUtils也可以用java 8轻松地写/读文件。