private final static String FILE_PATH="E:/abc.txt";
File file =newFile(FILE_PATH);//写入,wirte
OutputStream os =newFileOutputStream(file);
String s ="好好学习\r\n,天天向上";//在Windows\r\n是换行符
os.write(s.getBytes());
os.close();
二 : InputStream(读文件)
private final static String FILE_PATH="E:/abc.txt";/**is.read(byte[] b,int off,int off)
* 第一个参数是存放即将读出来的数据的字节数组。简称:数组b
* 第二个参数是偏移量,这里指将读出的字节插入到数组b的指定下标位置的偏移
* 量
*
* 第三个参数是要读取的最大长度。这个是指每一次读取在数组b中最多写入几个字节
*
*
* 如下面 off 和 len赋值后, 由于偏移量off为9每次读取数据后将字节从数组b下标为9
* 的 位置插入,因为len为2,所以每一次缓冲区最多只读入2个字节
*
*/
File file =newFile(FILE_PATH);
InputStream is =newFileInputStream(file);
byte[] b =newbyte[1024];//read中的参数第一个需要缓冲区,作为每次读多少.此处是对于 字节流的操作
int off =9;//数组位置偏移量(从哪里开始插入数据)
int len =2;//读取的最大字节数while(is.read(b, off, len)!=-1){
System.out.write(b, off, len);}
is.close();
2.1:为避免上述参数设置出现重复读,优化为下面代码:
File file =newFile(FILE_PATH);
InputStream is =newFileInputStream(file);
byte[] b =newbyte[10];//read中的参数第一个需要缓冲区,作为每次读多少.此处是对于 字节流的操作
int off =0;//数组位置偏移量(从哪里开始插入数据)
int len;//读取的最大字节数while((len = is.read(b))!=-1){
System.out.write(b, off, len);}
is.close();
总结
参数:
b - 存储读取数据的缓冲区。
off - 数据的起始偏移量。
len - 读取的最大字节数。
返回:读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。