对于只录入一行内容进行保存,很简单,想必大家都会,先看一下只录入一行的代码:
import java.io.*;
import java.util.*;
public class Text_2 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你要录入到文件中的内容:");
String a = sc.next();
FileOutputStream out = new FileOutputStream("c:\\javas\\kk\\Text2.txt");
byte [] b = a.getBytes();
out.write(b);
}
}
上面的代码是只能够运行一次,只能将一行代码写入到文件中去
显然是不够灵活的,那么下面看一下可以追加,可以换行,可以写多行内容到文件中去的完整源代码:
package text;
//2. 从键盘录入内容,并把内容保存到文件中。
import java.io.*;
import java.util.*;
public class Text_2_2 {
public static void main(String[] args) throws IOException {
String fileName = "c:\\javas\\kk\\Text_2_2.txt";//要写入的文件路径
File file = new File(fileName);
writeFile(file);
}
public static void writeFile(File file) throws IOException {
//判断是否有该文件路径
if(file.getParentFile().exists()) {
//判断是否有这个文件,没有就创建
if(!file.exists()) {
file.createNewFile();
}
//创建键盘录入对象
Scanner sc = new Scanner(System.in);
//获得键盘录入字符并判断
System.out.print("请输入你要录入的内容:");
String s = sc.nextLine();//这个nextLine方法可以接收空格当作字符串的内容
//String s = sc.next();----这个不可以接收空格,空格作为一个结束标志
while(!s.endsWith("end")) {//以“end”结尾的时候表示结束
//创建输出字节流
FileOutputStream fos = new FileOutputStream(file,true);
//利用转换流将输出字节流转换为字符流
OutputStreamWriter osw = new OutputStreamWriter(fos);
//将字符流转换为缓冲模式
BufferedWriter bw = new BufferedWriter(osw);
//写入
bw.write(s);
//换行
bw.newLine();
//关闭输出流
bw.close();
//再次接收键盘录入
System.out.print("请继续输出你要录入的内容:");
s=sc.nextLine();
}
}else {
System.out.println("你指定的路径不存在,请重新检查并修正");
}
}
}
如果你追求精致可以用上面的代码,如果你追求简介,可以用下面的代码块:
package text;
//2. 从键盘录入内容,并把内容保存到文件中。
import java.io.*;
import java.util.*;
public class Text_2_3 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
String str = null ;
FileWriter fw = new FileWriter("c:\\javas\\kk\\Text_2_3.txt");
BufferedWriter bw = new BufferedWriter(fw);
while(true) {
str=sc.next();
if(str.equals("end"))
break;
bw.write(str);
bw.newLine();
bw.flush();
}
bw.close();
}
}