举例在查找到的文件列表中所有带.java后缀的文件:
用到接口FilenameFilter(),并且实现方法accept(),返回值为boolean类型,涉及String类的indexOf()方法,返回找到的指定字符串的索引,如果找不到就返回-1。
class FileTest {
public static void main(String[] args) throws IOException, InterruptedException{
String strDir = File.separator;
String strAdd = "eclipse workplace" + strDir + "FileTest";
File f = new File(strDir,strAdd);
f.createNewFile();
String[] names = f.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
//indexOf(String string)
//Returns the first index of the given string, or -1.
return name.indexOf(".java")!=-1;
}
});
for(int i=0;i< names.length;i++){
System.out.println(names[i]);
}
}
}
结果:xiaohong_test.java
对文件的读写操作,通过输入流输出流
可从中读出一系列字节的对象称为输入流。而能向其中写入一系列字节的对象称为输出流。
InputStream(后续继续讲解)
三个基本的读方法
abstract int read() :读取一个字节数据,并返回读到的数据,如果返回-1,表示读到了输入流的末尾。注意以整形返回,是四个字节,只有第一个字节对我们来说才是有用的。
int read(byte[] b) :将数据读入一个字节数组,同时返回实际读取的字节数。如果返回-1,表示读到了输入流的末尾。
int read(byte[] b, int off, int len) :将数据读入一个字节数组,同时返回实际读取的字节数。如果返回-1,表示读到了输入流的末尾。off指定在数组b中存放数据的起始偏移位置;len指定读取的最大字节数。
其它方法(后续继续讲解)
long skip(long n) :在输入流中跳过n个字节,并返回实际跳过的字节数。用法:在读取一个字节流有时会发生堵塞,可以利用该方法来看下如果没有堵塞即正常情况下读取的字节数是多少。
int available() :返回在不发生阻塞的情况下,可读取的字节数。
void close() :关闭输入流,释放和这个流相关的系统资源。
void mark(int readlimit) :在输入流的当前位置放置一个标记,如果读取的字节数多于readlimit设置的值,则流忽略这个标记。
void reset() :返回到上一个标记。
boolean markSupported() :测试当前流是否支持mark和reset方法。如果支持,返回true,否则返回false。在使用这两个方法前先用本方法测试下支持不支持呀。
OutputStream
三个基本的写方法
abstract void write(int b) :往输出流中写入一个字节。
void write(byte[] b) :往输出流中写入数组b中的所有字节。
void write(byte[] b, int off, int len) :往输出流中写入数组b中从偏移量off开始的len个字节的数据。
其它方法
void flush() :刷新输出流,强制缓冲区中的输出字节被写出。只对使用了缓冲的流有效,因为CPU与硬盘交互效率没有CPU与内存区交互快,那么可以把要写的数据先写到缓冲区然后再统一写到硬盘上。
void close() :关闭输出流,释放和这个流相关的系统资源。
实例:利用System的in()和out()来对标准的输入设备的输入数据进行读写。
package StreamTest;
class StreamTest {
public static void main(String[] args) throws Exception{
int data;
while((data=System.in.read()) != -1){
System.out.write(data);
}
}
}
结果:
xiaohong
xiaohong
xiaofou
xiaofou