java语言对文件和文件夹的管理
创建File类对象,输出指定文件夹下的内容
package yuan;
import java.io.*;
public class APP10_9 {
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
String str = new String();
try(
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader inp = new BufferedReader(isr);
){
String sdir = "D:/Java";
String sfile;
File fdir1 = new File(sdir);
if(fdir1.exists() && fdir1.isDirectory()) {
System.out.println("文件夹"+sdir+"已经存在");
for(int i=0;i<fdir1.list().length;i++)
System.out.println((fdir1.list())[i]);
File fdir2 = new File("D:/Java/temp");
if(!fdir2.exists())
fdir2.mkdir();
System.out.println();
System.out.println("新建新文件夹后的文件列表");
for(int i =0;i<fdir1.list().length;i++)
System.out.println((fdir1.list())[i]);
}
System.out.println("请输入该文件夹中的一个文件名");
sfile = inp.readLine();
File ffile = new File(fdir1,sfile);
if(ffile.isFile()) {
System.out.println("文件名:"+ffile.getName());
System.out.println(";所在文件夹:"+ffile.getParent());
System.out.println(";文件大小"+ffile.length()+"字节");
}
}
catch(IOException e) {
System.out.println(e.toString());
}
}
}
对文件的随机访问
利用RandomAccessFile类对文件进行随机访问
package yuan;
import java.io.*;
import com.sun.org.apache.xerces.internal.util.SynchronizedSymbolTable;
public class APP10_10 {
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
StringBuffer stfDir =new StringBuffer();
System.out.println("请输入文件所在的路径");
char ch;
while((ch=(char)System.in.read())!='\r')
stfDir.append(ch);
File dir = new File(stfDir.toString());
System.out.println("请输入想要读取的文件名");
StringBuffer stfFileName = new StringBuffer();
char c;
while((c=(char)System.in.read())!='\r')
stfFileName.append(ch);
stfFileName.replace(0,1 , " "); //去掉上次输入并回车后存留在缓冲区中的"\n"
File readFrom = new File(dir,stfFileName.toString());
if(readFrom.isFile() && readFrom.canWrite() && readFrom.canRead()) {
RandomAccessFile rafFile = new RandomAccessFile(readFrom,"rw");
while(rafFile.getFilePointer()<rafFile.length())
System.out.println(rafFile.readLine());
rafFile.close();
}
else
System.out.println("文件不可读");
}
}