您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java语言深入 文件和流

2024/4/16 10:20:07发布21次查看
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语言深入 文件和流的内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product