java怎么把字符串写到文件里去

假如给一个字符串String s = "akjibuvuvu";怎么把这个s输出到文件a.txt
2024-11-22 21:36:18
推荐回答(2个)
回答(1):

String s = "akjibuvuvu";
FileWriter fw = null;
File f = new File("a.txt");

try {
if(!f.exists()){
f.createNewFile();
}
fw = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fw);
out.write(s, 0, s.length()-1);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("end");

回答(2):

package test;

public class ceshi {
private static final String fileName = "D://data.txt";
public static void main(String[] args) throws IOException {
System.out.println("请你输入一串字符,系统自动保存到D://data.txt文件中!下面请输入你的字串:");
//进行file的初始化...
File outputFile = new File(fileName);
if(!outputFile.exists()){
outputFile.createNewFile();
}
//捕捉控制台来的字符串..
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)), true);
String str = in.nextLine();
if (str != null && str.length() != 0) {
out.println(str);
}else{
out.println("你好,你没有在控制台输入任何字符!");
}
System.out.println("你好,请观察你的D盘下的data.txt文件,程序执行完毕.");
out.close();
in.close();
}
}