先理一理,Java中的流分两种,字节流和字符流,其中字节流的两个基类是InputStream和OutputStream;字符流的两个基类是Reader和Writer。所谓文件流,即我们对文件的操作留不开流。由此可知我们要用到某个类必然继承如上的四个基类之一。Java中一切都是类,一切都是对象。自然会想到文件操作有哪些类:
如下四个直接用到的类:
字节流中:FileInputStream和FileOutputStream
字符流中:FileReader和FileWriter
找到类就好办事了。剩下来的就是去找实现方法啦。
两种选择方案在这里,这就牵涉到我们如何选择合适的文件读写方式呢?
选择条件的区别:
以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
以字符为单位读取文件,常用于读文本,数字等类型的文件.
至于是否选择用Buffer来对文件输入输出流进行封装,就要看文件的大小,若是大文件的读写,则选择Buffer这个桶来提供文件读写效率。
1、运用字节流对文件进行直接读写:
注:FileOutputStream(file, true);里面true参数表示不覆盖原文件,直接在文件后面追加添加内容。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileTest
{
static File file = new File("C:\\Temp\\test.txt");
public static void main(String[] args)
{
try
{
FileOutputStream out = new FileOutputStream(file);
String s = "Hello,world!\r\n";
out.write(s.getBytes());
out.flush();
out.close();
FileInputStream in = new FileInputStream(file);
byte [] b = new byte[100];
in.read(b, 0, b.length);
System.out.println(new String(b));
in.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
2、运用字符流对文件进行直接读写:
public class FileTest
{
static File file = new File("C:\\Temp\\test.txt");
public static void main(String[] args)
{
try
{
FileWriter fw = new FileWriter(file,true);
fw.write("Hello,world!\r\n");
fw.flush();
fw.close();
BufferedReader br = new BufferedReader(new FileReader(file));
String data = null;
while((data = br.readLine())!=null)
{
System.out.println(data);
}
br.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
注意这里 BufferedReader 是对字符流封装后对文件进行读写,可以一行一行的读,比直接用FileReader快。
结合Scanner进行大文件的高效读写:
先看看Scanner类用于基本的从键盘输入的代码:
public class InputTest {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please input:");
while (s.hasNext()) {
String line = s.nextLine();
System.out.println(">>>" + line);
}
}
}
如果不是从键盘System.in 读入,而是直接处理一个字符串(注意这里是 s.next(), 不是s.nextLine() ):
public class InputTest {
public static void main(String[] args) {
Scanner s = new Scanner("Hello world!");
while (s.hasNext()) {
String line = s.next();
System.out.println(">>>" + line);
}
}
}
Scanner默认使用空格作为分割符来分隔文本,但允许你指定新的分隔符:
Scanner s = new Scanner("Hello:world!");
s.useDelimiter(":");
所以用Scanner来读取文件,可以吧上面程序中改为:
BufferedReader br = new BufferedReader(new FileReader(file));
Scanner s = new Scanner(br);
while(s.hasNextLine()){
System.out.println(s.nextLine());
}
br.close();
http://blog.csdn.net/sunnyfans/article/details/7706700
http://bbs.itheima.com/thread-90856-1-1.html