因为控制台输入,所以一般用文本处理就可以了这里是为了复习一下
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException {
System.out.println("请输入文本---");
File file = new File("D:/新建文本文档.txt");
InputStream in = System.in;
Scanner sc = new Scanner(in);
InputStreamReader isr = new InputStreamReader(in);//字节转换为字符
char []c= new char[1024*8];
int len = isr.read(c);
FileWriter fw = new FileWriter(file);
fw.write(new String(c,0,len));
fw.close();
sc.close();
}
}
如果是使用扫描器进行扫描—
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException {
System.out.println("请输入文本---");
File file = new File("D:/新建文本文档.txt");
InputStream in = System.in;
Scanner sc = new Scanner(in);
InputStreamReader isr = new InputStreamReader(in);//字节转换为字符
/* char[] c = new char[1024 * 8];
int len = isr.read(c);*/
FileWriter fw = new FileWriter(file);
// String next = sc.next();
String next = sc.nextLine();
while(sc.hasNext()) {
fw.write(next);
fw.flush();
next = sc.nextLine();
}
fw.close();
sc.close();
}
}
但是这种结果会有最由于一行没有写进文件中。
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException {
System.out.println("请输入文本---");
File file = new File("D:/新建文本文档.txt");
InputStream in = System.in;
Scanner sc = new Scanner(in);
InputStreamReader isr = new InputStreamReader(in);//字节转换为字符
/* char[] c = new char[1024 * 8];
int len = isr.read(c);*/
FileWriter fw = new FileWriter(file);
// String next = sc.next();
String next = sc.nextLine();
while(next!=null) {
fw.write(next);
fw.flush();
next = sc.nextLine();
}
fw.close();
sc.close();
}
}
所以,当next不为空的时候,就解决了上面的问题;
但是又有一个问题,什么时候结束录入呢?
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException {
System.out.println("请输入文本---");
File file = new File("D:/新建文本文档.txt");
InputStream in = System.in;
Scanner sc = new Scanner(in);
InputStreamReader isr = new InputStreamReader(in);//字节转换为字符
/* char[] c = new char[1024 * 8];
int len = isr.read(c);*/
FileWriter fw = new FileWriter(file);
// String next = sc.next();
String next = sc.nextLine();
while(!(next.equals("结束")|next.equals("exit"))) {
fw.write(next);
fw.write("\n");
fw.flush();
next = sc.nextLine();
}
fw.close();
sc.close();
}
}
while(!(next.equals(“结束”)|next.equals(“exit”)))我们可以换行后输入结束或者exit来作为结束的标志
其他-----为了加快读取和写入速度可以套上个缓冲管道;