编写一个Java应用程序,该程序读取从键盘输入的一行文本并将其存储到文件aaa.txt中

2024-12-12 20:54:32
推荐回答(2个)
回答1:

一个函数,希望可以给你点参考,从键盘读取的话使用Scanner类的nextLine方法即可,多看看java的api
public static void writeLogFile(String msg) {
try {
FileWriter fileWriter = new FileWriter("d:\\log.txt", true);// true代表追加
Date date = new Date();
fileWriter.write("["+date.toLocaleString()+"] ");
fileWriter.write(msg);
fileWriter.write("\n");
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println(msg);
}

回答2:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class OutputA {

public static void main(String [] args){
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
System.out.println("string's value is : "+s);
try {
BufferedWriter bw=new BufferedWriter(new FileWriter("d:\\aaa.txt"));
bw.write(s);
bw.flush();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}