java i/o系统的类实在是太多了,这里我们只学习一些基本的和常用的,相信能够把握这些就可以解决我们以后的普通应用了
1.什么是数据流 ?
数据流是指所有的数据通信通道
有两类流,inputstream and outputstream,java中每一种流的基本功能依靠于它们
inputstream 用于read,outputstream 用于write, 读和写都是相对与内存说的,读就是从其他地方把数据拿进内存,写就是把数据从内存推出去
这两个都是抽象类,不能直接使用
2.inputstream 的方法有:
read() 从流中读入数据 有3中方式:
int read() 一次读一个字节
int read(byte[]) 读多个字节到数组中
int read(byte[],int off,int len) 指定从数组的哪里开始,读多长
skip() 跳过流中若干字节
available() 返回流中可用字节数,但基于网络时无效,返回0
marksupported() 判定是否支持标记与复位操作
mark() 在流中标记一个位置,要与marksupported()连用
reset() 返回标记过的位置
close() 关闭流
3.outputstream 的方法:
write(int) 写一个字节到流中
write(byte[]) 将数组中的内容写到流中
write(byte[],int off,int len) 将数组中从off指定的位置开始len长度的数据写到流中
close() 关闭流
flush() 将缓冲区中的数据强制输出
4.file 类
file 可以表示文件也可以表示目录,file 类控制所有硬盘操作
构造器:
file(file parent,string child) 用父类和文件名构造
file(string pathname) 用绝对路径构造
file(string parent,string child) 用父目录和文件名构造
file(uri uri) 用远程文件构造
常用方法:
boolean createnewfile();
boolean exists();
例子:
//建立 test.txt 文件对象,判定是否存在,不存在就创建
import java.io.*;
public class createnewfile{
public static void main(string args[]){
file f=new file("test.txt");
try{
if(!f.exists())
f.createnewfile();
else
system.out.println("exists");
}catch(exception e){
e.printstacktrace();
}
}
}
boolean mkdir()/mkdirs()
boolean renameto(file destination)
例子://看一下这 mkdir()/mkdirs() 的区别和 renameto 的用法
import java.io.*;
public class createdir{
public static void main(string args[]){
file f=new file("test.txt");
file f1=new file("dir");
file f2=new file("top/bottom");
file f3=new file("newtest.txt");
try{
f.renameto(f3);
f1.mkdir();
f2.mkdirs();
}catch(exception e){
e.printstacktrace();
}
}
}
string getpath()/getabsolutepath()
string getparent()/getname()
例子://硬盘上并没有parent 目录和 test.txt 文件,但我们仍然可以操作,因为我们创建了他们的对象,是对对象进行操作
import java.io.*;
public class test{
public static void main(string args[]){
file f=new file("parent/test.txt");
file f1=new file("newtest.txt");
try{
system.out.println(f.getparent());
system.out.println(f.getname());
system.out.println(f1.getpath());
system.out.println(f1.getabsolutepath());
}catch(exception e){
e.printstacktrace();
}
}
}
以上就是Java语言深入 文件和流的内容,更多相关文章请关注PHP中文网(www.php.cn)!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号