读书人

Java资料操作实例浅析

发布时间: 2012-08-28 12:37:01 作者: rapoo

Java文件操作实例浅析

Java文件操作实例浅析

1. 实例一:创建文件和目录

在java.io包中有一个专门用于文件操作的类File类。此类提供了文件很多操作,如创建文件、删除文件、创建目录、删除目录等方法。

import java.io.File;

import java.io.IOException;

public class FileOperation1

{

publicstatic void main(String[] args)

{

//TODO Auto-generated method stub

Filef1=new File("d:\\test"); //在d盘上创建一个名为test的文件夹

Filef2=new File("11.txt"); //在当前路径下创建一个名为11.txt的文件

Filef3=new File("d:\\file.txt"); //在绝对路径下创建file.txt文件

Filef4=new File("d:\\","1.txt"); //前一个参数代表父路径,后一个参数代表子路径

booleansuc0=false;

booleansuc1=false;

booleansuc2=false;

booleansuc3=false;

booleansuc4=false;

booleansuc5=false;

booleansuc6=false;

try

{

suc0=f1.mkdir();//创建目录

suc1=f2.createNewFile();//创建指定文件,创建成功返回true,否则,返回false

suc2=f3.createNewFile();

suc3=f4.createNewFile();

}

catch(IOException e)

{

e.printStackTrace();

}

System.out.println(f1.isDirectory());//打印出f1是否为目录

System.out.println(suc1); //打印文件f2创建是否成功

System.out.println(f2.exists());//打印出文件f2是否存在,结果是true或者false;

System.out.println(f3.getAbsolutePath());//打印出f3的绝对路径名

System.out.println(f3.getName());//打印出f3的文件名

System.out.println(f3.getParent());//打印出f3的父路径

System.out.println(f4.isFile());//打印出f3是否为文件

System.out.println(f4.length());//打印出f3的长度

Filef5=new File("e:\\test\\abc"); //在e盘test文件夹下创建文件夹abc,此时在e盘上有test文件夹,则文件夹 abc创建成功,否则创建失败

if(f5.exists())f5.delete();

suc4=f5.mkdir();//创建目录

System.out.println(suc4);

Filef6=new File("e:\\aa.txt");

if(f6.exists())f6.delete(); //如果文件f6以前存在,则删除

try

{

suc5=f6.createNewFile();

}

catch(IOExceptione)

{

e.printStackTrace();

}

System.out.println(suc5);

suc6=f6.setReadOnly();//将文件f7设置为只读

System.out.println(suc6);

}

}

2. 实例二:显示文件夹中所有文件,包括该文件夹中子文件夹的文件

importjava.io.BufferedReader;

importjava.io.File;

importjava.io.IOException;

importjava.io.InputStreamReader;

publicclass FileOperation2

{

private void ShowAllFiles(File file)

{

String name=file.getName();

System.out.println(name);

if(file.isDirectory())

{

File[] files=file.listFiles(); //获取该文件夹中所有文件

int i;

for(i=0;i<files.length;i++)

{

ShowAllFiles(files[i]); //递归,递归终止条件是//file.isDirectory()==false

}

}

}

public static void main(String[] args) throwsIOException

{

// TODO Auto-generated method stub

BufferedReader br=new BufferedReader(newInputStreamReader(System.in));

System.out.println("请输入一个路径:");

String path=br.readLine();

File dirFile=new File(path);

if(dirFile.isDirectory()==false)

{

System.out.println("输入的不是合法路径,此目录不存在!");

System.exit(1);

}

FileOperation2 fo=new FileOperation2();

fo.ShowAllFiles(dirFile);

}

}

3. 实例三:读取文件

方案一:

importjava.io.FileInputStream;

importjava.io.IOException;

publicclass FileOperation3

{

final static int max=1024*1024;

public static void main(String[] args) throwsIOException

{

// TODO Auto-generated method stub

FileInputStream fis=null; //定义一个文件输入流

try

{

fis=newFileInputStream("e:\\11.txt"); //创建文件输入流,数据源是e:\\11.doc

byte[] data=new byte[max];

int i=0;

while(fis.read()!=-1)//当读输入流达到末尾时,read()方法返回-1

{

data[i++]=(byte)fis.read();//read()每次从输入流读取一个字节

}

String str=new String(data,0,i); //解析读取的数据

System.out.println(str); //显示读取的结果

}

catch(Exception e)

{

e.printStackTrace();

}

finally

{

fis.close(); //关闭输入流

}

}

}

方案二:

importjava.io.FileInputStream;

importjava.io.IOException;

publicclass FileException4

{

finalstaticintmax=1024*1024;

publicstaticvoid main(String[]args)throws IOException

{

//TODO Auto-generatedmethod stub

FileInputStreamfis=null;

fis=new FileInputStream("d:\\1.txt");

byte [] buff=newbyte[max];

int len=0;

try

{

len=fis.read(buff);

Stringstr=new String(buff,0,len);

System.out.println(str);

}

catch(Exception e)

{

e.printStackTrace();

}

finally

{

fis.close();

}

}

}

方案三:

importjava.io.FileInputStream;

importjava.io.FileReader;

importjava.io.IOException;

publicclass FileException5

{

finalstaticintmax=1024*1024;

publicstaticvoid main(String[]args)throws IOException

{

//TODO Auto-generatedmethod stub

FileReader fr=null;

fr=new FileReader("d:\\1.txt");

char [] buff=newchar[max];

int len=0;

try

{

len=fr.read(buff);

Stringstr=new String(buff,0,len);

System.out.println(str);

}

catch(Exception e)

{

e.printStackTrace();

}

finally

{

fr.close();

}

}

}

4. 实例四: 单线程下载程序

本实例共有4个类,分别是保存下载文件类、单线程下载类、单线程下载启动类和主界面类。

(1)保存下载文件类

import java.io.IOException;

import java.io.RandomAccessFile;

public class SaveDownloadFile //保存下载文件到本地随机文件类

{

privateRandomAccessFile localfile;

publicSaveDownloadFile()

{

localfile=null;

}

publicSaveDownloadFile(String filepath) throws IOException

{

localfile=newRandomAccessFile(filepath,"rw");

}

public void write(byte[] buff,intstart,int length) //可供多个线程使用的方法

{

try

{

this.localfile.write(buff,start, length);

}

catch(IOExceptione)

{

e.printStackTrace();

}

}

publicvoid close()

{

try

{

if(this.localfile!=null)this.localfile.close();

}

catch(Exceptione)

{

e.printStackTrace();

}

}

}

(2)单线程下载类

import java.io.IOException;

import java.net.HttpURLConnection;

import java.net.URL;

importorg.omg.CORBA.portable.InputStream;

public class SingleThreadDownloadextends Thread

//每个线程将下载的内容保存到本地随机访问文件中

{

privateString url; //URL

private String savefilepath; //保存为本地随机文件绝对路径

privateSaveDownloadFile sdf; //本地随机访问文件的对象

privatestatic URL url_obj;

privatestatic HttpURLConnection conn;

privatestatic java.io.InputStream is;

privatefinal static int buffsize=1024*1024;

//定义下载缓冲区大小

privatebyte[] buff; //下载的缓冲区

public SingleThreadDownload(Stringurl,String savefilepath)

{

super();

this.url=url;

this.savefilepath=savefilepath;

try

{

this.sdf=newSaveDownloadFile(savefilepath);

buff=newbyte[buffsize];

url_obj=newURL(this.url);

conn=(HttpURLConnection)url_obj.openConnection();

conn.setReadTimeout(10000);//设置读取数据超时

is=conn.getInputStream();

}

catch(Exceptione)

{

e.printStackTrace();

}

}

publicvoid run()

{

try

{

intlength=0;

while((length=is.read(buff))>0)

{

this.sdf.write(buff,0, length);

}

System.out.println("下载已经完成!");

}

catch(Exceptione)

{

e.printStackTrace();

}

finally

{

this.sdf.close();

try

{

is.close();

}

catch(Exception e)

{

//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

(3)单线程下载启动类

import java.io.IOException;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

public class SingleThreadDownloadStartimplements Runnable

{

privateString url;

privateString savefilepath; //下载文件保存的绝对路径

privateSingleThreadDownload std;

SingleThreadDownloadStart(Stringurl,String savefilepath)

{

this.url=url;

this.savefilepath=savefilepath;

this.std=new SingleThreadDownload(url,savefilepath);

}

publicvoid run()

{

//TODO Auto-generated method stub

this.std.start();

}

}

(4)主界面类

import java.io.BufferedReader;

import java.io.File;

import java.io.IOException;

import java.io.InputStreamReader;

public class Mainclass //主类

{

privateString url; //下载的URL

privateString pathname; //下载文件要保存的本地路径,此路径可能包含文件名

privateString downloadfilename; //下载文件的名,从url抽取的文件名

privateString savefilename=null; //下载后保存的文件名

privateSingleThreadDownloadStart stds;

Mainclass(Stringurl,String pathname)

{

CheckURL(url);

CheckPathname(pathname);

this.stds=newSingleThreadDownloadStart(this.url,this.pathname);

this.stds.run();

}

voidCheckURL(String url)

{

intpos=url.lastIndexOf("/"); //获取字符"/"出现的最后一个位置

if(pos>=url.length()-1) //此时说明/后已经没有字符串了

{

System.out.println("URL不合法!");

System.exit(1);

}

else

{

this.downloadfilename=url.substring(pos+1,url.length()); //获取下载的文件名

if(this.downloadfilename.contains(".")==false)

{

System.out.println("URL不合法");

System.exit(1);

}

this.url=url;

}

}

voidCheckPathname(String pathname)

{

File[] roots=File.listRoots(); //获取Windows下所有盘符

if(pathname.contains("\\")==false)

{

System.out.println("要保存的路径不合法!");

System.exit(1);

}

int i;

booleanexist=false;

for(i=0;i<roots.length;i++)

{

Stringupper=roots[i].toString();

Stringlower=upper.toLowerCase();

if(pathname.contains(upper)==true|| pathname.contains(lower)==true) exist=true;

}

if(exist==false)

{

System.out.println("要保存的路径不合法!");

System.exit(1);

}

this.pathname=pathname;

i=pathname.lastIndexOf("\\");

if(i<pathname.length()-1) this.savefilename=pathname.substring(i+1, pathname.length());

else //pathname不包含文件名

{

this.savefilename=this.downloadfilename;

this.pathname+=this.savefilename;

}

}

finalpublic void Show()

{

System.out.println("下载文件名:"+this.downloadfilename);

System.out.println("保存的文件名:"+this.savefilename);

System.out.println("下载要保存的路径名:"+this.pathname);

}

publicstatic void main(String[] args) throws IOException

{

//TODO Auto-generated method stub

BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));

System.out.println("请输入URL=");

Stringurl=br.readLine();

System.out.println("请输入要下载文件的路径名:");

Stringpathname=br.readLine();

Mainclassmainclass=new Mainclass(url,pathname);

mainclass.Show();

}

}

5. 对象序列化实例:读取和保存对象

(1) 测试类A

importjava.io.Serializable;

publicclassTestClassA implements Serializable

{

privatestaticfinallongserialVersionID=11111111;

private TestClassBb;

publicfinal TestClassB get()

{

returnb;

}

publicvoid set(TestClassB b)

{

this.b=b;

}

}

(2) 测试类B

importjava.io.Serializable;

publicclassTestClassB implements Serializable

{

privatestaticfinallongserialVersionID=00000000;

private Stringstr;

publicfinal String get()

{

returnstr;

}

publicvoid set(String str)

{

this.str=str;

}

}

(3) 序列化测试类

importjava.io.BufferedReader;

importjava.io.FileInputStream;

importjava.io.FileOutputStream;

importjava.io.InputStreamReader;

importjava.io.ObjectInputStream;

import java.io.ObjectOutputStream;

publicclass SerializeTest

{

publicvoid SaveObject(Objecto,String filepath)

{

FileOutputStreamfos=null;//定义文件输出流

ObjectOutputStreamos=null;//定义对象输出流

try

{

fos=newFileOutputStream(filepath);

os=new ObjectOutputStream(fos);

long StartTime=System.currentTimeMillis();

//获取系统当前时间

os.writeObject(o);

System.out.println("对象保存时间:"+(System.currentTimeMillis()-StartTime));

}

catch(Exception e)

{

e.printStackTrace();

}

finally

{

try

{

os.flush();

System.out.println("对象保存成功!");

os.close();

fos.close();

}

catch(Exception e)

{

e.printStackTrace();

}

finally

{

fos=null;

os=null;

}

}

}

publicfinal ObjectGetObject(String filepath)

{

FileInputStreamfis=null;//定义文件输入流

ObjectInputStreamis=null;//定义对象输入流

Objecto=null;

try

{

fis=newFileInputStream(filepath);

is=newObjectInputStream(fis);

long StartTime=System.currentTimeMillis();

//获取系统当前时间

o=is.readObject();

System.out.println("对象保存时间:"+(System.currentTimeMillis()-StartTime));

}

catch(Exception e)

{

e.printStackTrace();

}

finally

{

System.out.println("对象读取成功!");

try

{

is.close();

fis.close();

}

catch(Exception e)

{

e.printStackTrace();

}

finally

{

is=null;

fis=null;

}

}

return o;

}

publicstaticvoid main(String[]args)

{

TestClassAa=new TestClassA();

TestClassB b=newTestClassB();

b.set("HelloWorld, I am Wangzhicheng!");

a.set(b);

BufferedReaderbr=new BufferedReader(newInputStreamReader(System.in));

Stringfilepath=null;

try

{

filepath=br.readLine();

}

catch(Exception e)

{

e.printStackTrace();

}

SerializeTestst=new SerializeTest();

st.SaveObject(a,filepath);

TestClassAcopyA=(TestClassA)st.GetObject(filepath);

System.out.println(copyA.get().get());

}

}

读书人网 >编程

热点推荐