字节流
字节流主要是操作byte类型数据,以byte数组为准,主要操作类就是OutputStream、InputStream
字节输出流:
6 public class Test11 {
7 public static void main(String[] args) throws IOException {
8 File f = new File("d:" + File.separator+"test.txt");
9 OutputStream out=new FileOutputStream(f);//如果文件不存在会自动创建,如果要追加的话,在构造方法里加true
10 String str="Hello World";
11 byte[] b=str.getBytes();
12 out.write(b);//因为是字节流,所以要转化成字节数组进行输出
13 out.close();
14 }
15 }
字节输入流:InputStream
6 public class Test12 {
7 public static void main(String[] args) throws IOException {
8 File f = new File("d:" + File.separator+"test.txt");
9 InputStream in=new FileInputStream(f);
10 byte[] b=new byte[1024];
11 int len=in.read(b);
12 in.close();
13 System.out.println(new String(b,0,len));
14 }
15 }
字符流
在程序中一个字符等于两个字节,那么java提供了Reader、Writer两个专门操作字符流的类。
字符输出流:Writer
Writer本身是一个字符流的输出类,此类的定义如下:
public abstract class Writer extends Object implements Appendable,Closeable,Flushable
此类本身也是一个抽象类,如果要使用此类,则肯定要使用其子类,此时如果是向文件中写入内容,所以应该使用FileWriter的子类。
FileWriter类的构造方法定义如下:
public FileWriter(File file)throws IOException
字符流的操作比字节流操作好在一点,就是可以直接输出字符串了,不用再像之前那样进行转换操作了。
6 public class Test16 {7 public static void main(String[] args) throws IOException {
8 File f = new File("d:" + File.separator+"test.txt");
9 Writer out=new FileWriter(f);
10 String str="Hello World";
11 out.write(str);
12 out.close();
13 }
14 }
字符输入流:Reader
Reader是使用字符的方式从文件中取出数据,Reader类的定义如下:
public abstract class Reader extends Objects implements Readable,Closeable
Reader本身也是抽象类,如果现在要从文件中读取内容,则可以直接使用FileReader子类。
FileReader的构造方法定义如下:
public FileReader(File file)throws FileNotFoundException
以字符数组的形式读取出数据:
6 public class Test18 {7 public static void main(String[] args) throws IOException {
8 File f = new File("d:" + File.separator+"test.txt");
9 Reader input=new FileReader(f);
10 char[] c=new char[1024];
11 int len=input.read(c);
12 input.close();
13 System.out.println(new String(c,0,len));
14 }
15 }