Java中,怎样把一段文字写入一个文本文件中?

希望高手可以给出一个例子,比如我想把下边的文字写入到文本文件中:

12345
abcde
123.abc

我的思路是先把这3行字符输入到一个集合中,然后再存入文本文件中。但是一直不知道从何下手。刚学Java,请多指教。
多谢各位了。

参考下面代码,把“百度知道”写到D盘的写入文字.txt中

import java.io.*;

public class C {
    public static void main( String[ ] args ) throws Exception {
        PrintWriter pw = new PrintWriter( new FileWriter( "D:\\写入文字.txt" ) );
        pw.print("百度知道" );
        pw.close();
    }
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2010-05-25
你打开一个文件夹,用一个输出流关联着,然后直接将三行内容输出到文件后,再关闭文件和输出流就可以了。
还有什么不懂可以再问
第2个回答  推荐于2018-02-26
import java.io.FileWriter;
import java.io.IOException;

public class TestFile {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer();
sb.append("12345\n");
sb.append("abcde\n");
sb.append("123.abc");
try {
FileWriter fw=new FileWriter("c:/test.txt");
fw.write(sb.toString());
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}本回答被提问者和网友采纳
第3个回答  2019-02-15
使用java中的file类,url为文件的绝对地址,str为输入的字符串内容。
代码如下:
string
str="i
love
china!"
file
txt=new
file("url");
if(!txt.exists()){
txt.createnewfile();
}
byte
bytes[]=new
byte[512];
bytes=str.getbytes();
//新加的
int
b=str.length();
//改
fileoutputstream
fos=new
fileoutputstream(txt);
fos.write(bytes,0,b);
fos.close();
第4个回答  2010-05-25
import java.io.*;

public class C {
public static void main( String[ ] args ) throws Exception {
PrintWriter pw = new PrintWriter( new FileWriter( "D:\\问好.txt" ) );
pw.print("你好" );
pw.close();
}
}

其中D:\\问好.txt是你要存的文件名字,
pw.print("你好" );是你要存入文件的内容,这是最简单的了
相似回答