用Java编写文本文件的最简单方法是什么? [英] What is the simplest way to write a text file in Java?

查看:116
本文介绍了用Java编写文本文件的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道用Java编写文本文件最简单(最简单)的方法是什么.请保持简单,因为我是初学者:D

I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D

我在网上搜索并找到了此代码,但我了解其中的50%.

I searched the web and found this code, but I understand 50% of it.

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

}

推荐答案

在Java 7及更高版本中,使用

With Java 7 and up, a one liner using Files:

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

这篇关于用Java编写文本文件的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆