您的位置:首页 > 其它

文件读写操作笔记

2015-08-21 16:04 239 查看

文件读写操作:

一.获得控制台用户输入的信息

public String getInputMessage() throws IOException...{

System.out.println("请输入您的命令∶");

byte buffer[]=new byte[1024];

int count=System.in.read(buffer);

char[] ch=new char[count-2];//最后两位为结束符,删去不要

for(int i=0;i<count-2;i++)

ch[i]=(char)buffer[i];

String str=new String(ch);

return str;

}

可以返回用户输入的信息,不足之处在于不支持中文输入,有待进一步改进。

二.复制文件

1.以文件流的方式复制文件

public void copyFile(String src,String dest) throws IOException...{

FileInputStream in=new FileInputStream(src);

File file=new File(dest);

if(!file.exists())

file.createNewFile();

FileOutputStream out=new FileOutputStream(file);

int c;

byte buffer[]=new byte[1024];

while((c=in.read(buffer))!=-1)...{

for(int i=0;i<c;i++)

out.write(buffer[i]);

}

in.close();

out.close();

}

该方法经过测试,支持中文处理,并且可以复制多种类型,比如txt,xml,jpg,doc等多种格式

三.写文件

1.利用PrintStream写文件

public void PrintStreamDemo()...{

try ...{

FileOutputStream out=new FileOutputStream("D:/test.txt");

PrintStream p=new PrintStream(out);

for(int i=0;i<10;i++)

p.println("This is "+i+" line");

} catch (FileNotFoundException e) ...{

e.printStackTrace();

}

}

2.利用StringBuffer写文件

public void StringBufferDemo() throws IOException......{

File file=new File("/root/sms.log");

if(!file.exists())

file.createNewFile();

FileOutputStream out=new FileOutputStream(file,true);

for(int i=0;i<10000;i++)......{

StringBuffer sb=new StringBuffer();

sb.append("这是第"+i+"行:前面介绍的各种方法都不关用,为什么总是奇怪的问题 ");

out.write(sb.toString().getBytes("utf-8"));

}

out.close();

}

该方法可以设定使用何种编码,有效解决中文问题。

四.文件重命名

public void renameFile(String path,String oldname,String newname)...{

if(!oldname.equals(newname))...{//新的文件名和以前文件名不同时,才有必要进行重命名

File oldfile=new File(path+"/"+oldname);

File newfile=new File(path+"/"+newname);

if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名

System.out.println(newname+"已经存在!");

else...{

oldfile.renameTo(newfile);

}

}

}

五.转移文件目录

转移文件目录不等同于复制文件,复制文件是复制后两个目录都存在该文件,而转移文件目录则是转移后,只有新目录中存在该文件。

public void changeDirectory(String filename,String oldpath,String newpath,boolean cover)...{

if(!oldpath.equals(newpath))...{

File oldfile=new File(oldpath+"/"+filename);

File newfile=new File(newpath+"/"+filename);

if(newfile.exists())...{//若在待转移目录下,已经存在待转移文件

if(cover)//覆盖

oldfile.renameTo(newfile);

else

System.out.println("在新目录下已经存在:"+filename);

}

else...{

oldfile.renameTo(newfile);

}

}

}

六.读文件

1.利用FileInputStream读取文件

public String FileInputStreamDemo(String path) throws IOException...{

File file=new File(path);

if(!file.exists()||file.isDirectory())

throw new FileNotFoundException();

FileInputStream fis=new FileInputStream(file);

byte[] buf = new byte[1024];

StringBuffer sb=new StringBuffer();

while((fis.read(buf))!=-1)...{

sb.append(new String(buf));

buf=new byte[1024];//重新生成,避免和上次读取的数据重复

}

return sb.toString();

}

2.利用BufferedReader读取

在IO操作,利用BufferedReader和BufferedWriter效率会更高一点

public String BufferedReaderDemo(String path) throws IOException...{

File file=new File(path);

if(!file.exists()||file.isDirectory())

throw new FileNotFoundException();

BufferedReader br=new BufferedReader(new FileReader(file));

String temp=null;

StringBuffer sb=new StringBuffer();

temp=br.readLine();

while(temp!=null)...{

sb.append(temp+" ");

temp=br.readLine();

}

return sb.toString();

}

3.利用dom4j读取xml文件

public Document readXml(String path) throws DocumentException, IOException...{

File file=new File(path);

BufferedReader bufferedreader = new BufferedReader(new FileReader(file));

SAXReader saxreader = new SAXReader();

Document document = (Document)saxreader.read(bufferedreader);

bufferedreader.close();

return document;

}

七.创建文件(文件夹)

1.创建文件夹

public void createDir(String path)...{

File dir=new File(path);

if(!dir.exists())

dir.mkdir();

}

2.创建新文件

public void createFile(String path,String filename) throws IOException...{

File file=new File(path+"/"+filename);

if(!file.exists())

file.createNewFile();

}

八.删除文件(目录)

1.删除文件

public void delFile(String path,String filename)...{

File file=new File(path+"/"+filename);

if(file.exists()&&file.isFile())

file.delete();

}

2.删除目录

要利用File类的delete()方法删除目录时,必须保证该目录下没有文件或者子目录,否则删除失败,因此在实际应用中,我们要删除目录,必须利用递归删除该目录下的所有子目录和文件,然后再删除该目录。

public void delDir(String path)...{

File dir=new File(path);

if(dir.exists())...{

File[] tmp=dir.listFiles();

for(int i=0;i<tmp.length;i++)...{

if(tmp[i].isDirectory())...{

delDir(path+"/"+tmp[i].getName());

}

else...{

tmp[i].delete();

}

}

dir.delete();

}

}

九、read

JDK中的解释

public int read(byte[] b)
throws IOException

从此输入流中将最多
b.length
个字节的数据读入一个 byte 数组中。在某些输入可用之前,此方法将阻塞。
覆盖:类
InputStream
中的
read


参数:
b
- 存储读取数据的缓冲区。
返回:读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回
-1
。抛出:
IOException
- 如果发生 I/O 错误。另请参见:
InputStream.read(byte[], int, int)


注意:

1.buffer数组的长度就是read执行一次读入的大小,如果成功,那么数组存储读入的数据,并且方法返回读入数据的大小(就是数组大小)。

2、如果剩余读入的数据大小(利用available()来判定剩余数据的大小)小于数组长度,那么read()返回值就是-1。

3、重要的是,read循环读入时候,并不会先清空数组后再读入,而是直接覆盖需要的数组元素,如果read()方法返回是-1,那么用于存储的数组后几位将是上一次循环中read()所存储的内容,不能完全覆盖掉数组中的数据。所以最后一次不能直接write(Buffer),而是应该计算出剩余数据大小并且fileOutputStream.write(remain);而不使用buffer。

十、java中的getParentFile

String name = "AAAA.txt";

String lujing = "1"+"/"+"2";//定义路径

File a = new File(lujing,name);

a.getParentFile().mkdirs(); //这里如果不加getParentFile(),创建的文件夹为"1/2/AAAA.txt/"

那么,a的意义就是“1/2/AAAA.txt”。

这里a是File,但是File这个类在Java里表示的不只是文件,虽然File在英语里是文件的意思。Java里,File至少可以表示文件或文件夹(大概还有可以表示系统设备什么的,这里不考虑,只考虑文件和文件夹)。

也就是说,在“1/2/AAAA.txt”真正出现在磁盘结构里之前,它既可以表示这个文件,也可以表示这个路径的文件夹。那么,如果没有getParentFile(),直接执行a.mkdirs(),就是说,创建“1/2/AAAA.txt”代表的文件夹,也就是“1/2/AAAA.txt/”,在此之后,执行a.createNewFile(),试图创建a文件,然而以a为名的文件夹已经存在了,所以createNewFile()实际是执行失败的。你可以用System.out.println(a.createNewFile())这样来检查是不是真正创建文件成功。

所以,这里,你想要创建的是“1/2/AAAA.txt”这个文件。在创建AAAA.txt之前,必须要1/2这个目录存在。所以,要得到1/2,就要用a.getParentFile(),然后要创建它,也就是a.getParentFile().mkdirs()。在这之后,a作为文件所需要的文件夹大概会存在了(有特殊情况会无法创建的,这里不考虑),就执行a.createNewFile()创建a文件。

十一、RandomAccessFile的使用

Java的RandomAccessFile提供对文件的读写功能,与普通的输入输出流不一样的是RamdomAccessFile可以任意的访问文件的任何地方。这就是“Random”的意义所在。

RandomAccessFile的对象包含一个记录指针,用于标识当前流的读写位置,这个位置可以向前移动,也可以向后移动。RandomAccessFile包含两个方法来操作文件记录指针。

long getFilePoint():记录文件指针的当前位置。

void seek(long pos):将文件记录指针定位到pos位置。

RandomAccessFile包含InputStream的三个read方法,也包含OutputStream的三个write方法。同时RandomAccessFile还包含一系列的readXxx和writeXxx方法完成输入输出。

RandomAccessFile的构造方法如下



mode的值有四个

"r":以只读文方式打开指定文件。如果你写的话会有IOException。

"rw":以读写方式打开指定文件,不存在就创建新文件。

"rws":不介绍了。

"rwd":也不介绍。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: