文件字节流与文件字符流

文件字节流

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

public class test1 {

public static void main(String[] args) {

File file = new File("hello.txt");

byte b[] = "欢迎welcome".getBytes();

try {

/**

 * 构造方法如下:

 * FileOutputStream(String name);

 * FileOutputStream(File file);

 * FileOutputStream构造方法参数指定的文件称为输出流的目的地

 * 如果输出流指向的文件不存在,java就会创建该文件

 * 如果指向的文件已存在,输出流就将刷新该文件

 * FileOutputStream(String name, boolean append);

 * FileOutputStream(File file, boolean append);

 * 对于这两个构造函数,如果参数append取值true,输出流不会刷新所指向的文件

 */

FileOutputStream out = new FileOutputStream(file);

/**

 * 输出流使用write方法把数据写入输出流到达目的地

 * write()的用法如下

 * public void write(byte b[])--写b.length个字节到输出流

 * public void write(byte b[],int off, int len)--从给定字节数组中

 * 起始于偏移量off处写len个字节到输出流

 * 只要不关闭流,每次调用write方法就顺序地向文件写入内容,直到流被关闭

 */

out.write(b);

out.write(b,2,2);

/**

 * 向hello.txt文件中输入内容:欢迎welcome迎

 * 注意:一个汉字占两个字节,英文字母占一个字节

 */

out.close();

/**

 * FileInputStream构造方法如下:

 * FileInputStream(String name);

 * FileInputStream(File file);

 * 构造方法参数指定的文件称为输入流的源,输入流

 * 通过使用read()方法从输入流读出源中的数据

 */

FileInputStream in = new FileInputStream(file);

int n=0;

/**

 * read()方法从输入流中顺序读取单个字节的数据,读取位置到底文件末尾则返回-1;

 * FileInputStream流顺序地读取文件,只有不关闭流,每次

 * 调用read()方法就顺序地读取文件中的其余内容,

 * 直到文件的末尾或流被关闭

 */

while((n=in.read(b)) != -1){

String str = new String(b,0,n);

System.out.println(n);

System.out.println(str);

}

catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

文件字符流

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

public class test2 {

/**

 * @param args

 * 简要解析文件字符流的用法,以及一些常用的方法的用法

 * FileReader与FileWriter类

 * 用法与文件字节流相似,可以参考使用

 */

public static void main(String[] args) {

// TODO Auto-generated method stub

File file = new File("hello.txt");

char b[] = "欢迎welcome".toCharArray();

try {

FileWriter out = new FileWriter(file,true);

out.write(b);

out.write("来到北京");

out.close();

FileReader in = new FileReader(file);

int n=0;

//while((n = in.read(b,0,2)) != -1){

//String str = new String(b,0,n);

//System.out.println(str);

//}

while((n=in.read(b)) != -1){

String str = new String(b,0,n);

System.out.println(n);

System.out.println(str);

}

in.close();

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值