文件操作

来源:互联网 发布:软件咨询服务合同 编辑:程序博客网 时间:2024/04/29 11:28
文件操作

//用缓冲字节流实现文件读写

import java.io.*;public class BufferedStreamTest { /**  * @param args  */ public static void main(String[] args) { // TODO Auto-generated method stub try { FileOutputStream fos = new  FileOutputStream("res/bufferFile"); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dos = new DataOutputStream(bos); dos.writeUTF("hello world"); dos.writeBoolean(false); dos.writeInt(125); dos.flush();//清空缓冲区fos.close(); fos.close(); dos.close();


 

 

/*需要注意的是,由于读写顺序是从最外面开始读取也就是说从数据输出流DataOutputStream 开始读取,其次是缓冲输出流BufferedOutputStream,再其次是文件输出流FileOutStream,所以如果不写d os.flush 只要保证关闭的顺序正确也是可以正确运行的,即:dos.close();bos.close();fos.close();*/FileInputStream fis = new              FileInputStream("res/bufferFile");BufferedInputStream bis = new BufferedInputStream(fis);DataInputStream dis = new DataInputStream(bis);System.out.println(dis.readUTF()+"\n"+dis.readBoolean()+"\n"+d is.readInt());//输出时注意与输入时保持一致fis.close();bis.close();dis.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


//新增文档 bufferFile 直接查看会出现乱码问题,这是正常的,由于文档将字符型、布尔型、整型等放在一起使文档无法识别出现乱码,但是文档输出是正确的。

在写这段代码的时候,我们遇到了问题,由于没有提前清空缓冲数据,导致程序运行错误,后来找到了错误的原因,原因是:

Flush()主要用在IO中,即清空缓冲区数据,就是说你用读写流的时候,其实数据是先被读到了内存中,然后用数据写到文件中,当你数据读完的时候不代表你的数据已经写完了,因为还有一部分有可能会留在内存这个缓冲区中。这时候如果你调用了 Close()方法关闭了读写流,那么这部分数据就会丢失,所以应该在关闭读写流之前先Flush(),先清空数据。

文件操作类

文件类(File)提供处理文件的方法,包括:更改文件名、删除文件、列出目录下的文件以及文件对象属性的描述信息等。

public   File(String  pathname);根据parent抽象路径名和child路径名字符串创建一个新的File对象

public   File(String path,String name);根据parent路径名字符串和child路径名字符串创建一个新File对象

public   File(File  parent,String chile);通过指定路径名字字符串转换为抽象路径名来创建一个新的File 对象

感觉有点绕啊.......通过实例来解决,其实还是很简单的

Source.txt

Backup\source.txt

执行备份:

1、判断目录备份是否存在,如无 建立目录①backup②将源文件复制到backup;如有:判断是否需要备份,如有必要:将源文件复制到backup,如没必要

其他方法

  (1)访问文件对象

l public String getName()  //返回文件对象名,不包含路径名

l public String getPath()    //返回相对路径名,包含文件名

l public String getAbsolutePath()   //返回绝对路径名,包含文件名

l public String getParent()      //返回父文件对象的路径名

l public File   getParentFile()    //返回父文件对象

(2)获得文件属性

l public long length()     //返回指定文件的字节长度

l public boolean exists()    //测试指定的文件是否存在

l public long lastModified()   //返回指定文件最后被修改的时间

 (3)文件操作

l public boolean renameTo(Filedest)  //文件重命名

l public boolean  delete()   //删除空目录

 (4)目录操作

l public boolean mkdir () //创建指定日录,正常建立时返回true

l public String[] list()    //返回目录中的所有文件名字符串

l public File[] listFiles()    //返回指定目录中的所有文件对象

感觉有点绕啊.......通过实例来解决,其实还是很简单的

例子如下:

//生成目录文件和输出目录文件

由于操作非常简单,按照方法就能实现,在这里就不做演示了

//利用File自动更新文件package DataStream;import java.io.*;import java.text.SimpleDateFormat;import java.util.Date;public class FileUpdateTest {public static void main(String[] args) throws IOException{//待复制的文件名String fname = "source.txt";//目标目录名String destdir = "backup" ;update(fname,destdir);}private static void update(String fname, String destdir) throws IOException{// TODO Auto-generated method stubFile f1,f2,dest;//在当前目录中创建文件对象 f1,destf1 = new File(fname);dest = new File(destdir);if(f1.exists()){//dest不存在时创建目录if(!dest.exists()){System.out.println("dest不存在,创建backup");dest.mkdir();}//在目录dest中创建文件f2f2=new File(dest,fname);long d1 = f1.lastModified();long d2 = f2.lastModified();//f2 不存在时或存在但日期较早时if((!f2.exists())||(f2.exists()&&(d1>d2))){copy(f1,f2);//复制}showFileInfo(f1);showFileInfo(dest);}else{System.out.println(f1.getName()+"file not found");}}public static void showFileInfo(File f1) throws IOException{// TODO Auto-generated method stubSimpleDateFormat sdf;sdf = new SimpleDateFormat("yyyy年MM月dd日hh时mm分");if(f1.isFile()){String filepath = f1.getAbsolutePath();Date da  = new Date(f1.lastModified());String mat = sdf.format(da);System.out.println("<文件:>\t"+filepath+"\t"+f1.length()+"\t"+mat);}else{System.out.println("<目录:>"+"\t"+f1.getAbsolutePath());File[]files = f1.listFiles();for(int i = 0;i<files.length;i++){showFileInfo(files[i]);}}}public static void copy(File f1, File f2) throws IOException {// TODO Auto-generated method stub//创建文件输入流对象FileInputStream fis = new FileInputStream(f1);//创建文件输入流对象FileOutputStream fos = new FileOutputStream(f2);int count,n=512;byte buffer[] = new byte[n];//从输入流读取数据count = fis.read(buffer,0,n);while(count!=-1){//写出输出流数据fos.write(buffer,0,count);count = fis.read(buffer,0,n);}System.out.println("复制文件"+f2.getName()+"成功!");//关闭输入\输出流fis.close();fos.close();}}


 

 

 import java.awt.*;import javax.swing.*;import java.awt.event.*;import java.io.*;public class NotepadTest extends JFrame implements ActionListener{Container c;JTextArea ta;JScrollPane jsp;JMenuBar menubar;JMenu menuFile,menuEdit;JMenuItem open,save,exit,copy,paste;JFileChooser filechooser;File file = null;String clipboardstr = "";public NotepadTest(){super("记事本");ta = new JTextArea(30,100);jsp = new JScrollPane(ta);menubar = new JMenuBar();menuFile = new JMenu("文件");menuEdit = new JMenu("编辑");open =  new JMenuItem("打开");save = new JMenuItem("保存");exit = new JMenuItem("退出");copy = new JMenuItem("复制");paste = new JMenuItem("粘贴");this.setJMenuBar(menubar);menubar.add(menuFile);menubar.add(menuEdit);menuFile.add(open);open.addActionListener(this);menuFile.add(save);save.addActionListener(this);menuFile.add(exit);exit.addActionListener(this);menuEdit.add(copy);copy.addActionListener(this);menuEdit.add(paste);paste.addActionListener(this);c = this.getContentPane();c.setLayout(new GridLayout(1,1));c.add(jsp);filechooser = new JFileChooser();this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);this.setSize(800,600);this.setVisible(true);}class txtFilter extends javax.swing.filechooser.FileFilter{public boolean accept(File file){return file.getName().toLowerCase().endsWith(".txt")||file.isDirectory();}public String getDescription(){return".txt";}}public void actionPerformed(ActionEvent e){txtFilter filter = new txtFilter();Object obj = e.getSource();JMenuItem item = (JMenuItem)obj;if(item==open){try{filechooser.addChoosableFileFilter(filter);int result = filechooser.showOpenDialog(this);file = filechooser.getSelectedFile();if((result==JFileChooser.APPROVE_OPTION)&&(file!=null)){FileReader fr = new FileReader(file);BufferedReader br = new BufferedReader(fr);ta.setText("");String line;while((line=br.readLine())!=null){ta.setFont(new Font("宋体",Font.PLAIN,20));ta.append(line+"\n");}fr.close();br.close();}}catch(IOException ie){System.out.println(ie.getMessage());}catch(Exception ec){System.out.println(ec.getMessage());}}if(item==save){try{filechooser.addChoosableFileFilter(filter);int result=filechooser.showSaveDialog(this);file=filechooser.getSelectedFile();if((result==JFileChooser.APPROVE_OPTION)&&(file!=null)){FileWriter fw=new FileWriter(file+".txt");BufferedWriter bw=new BufferedWriter(fw);String content = ta.getText();bw.write(content,0,content.length());bw.flush();fw.close();bw.close();}}catch(IOException ie){System.out.println(ie.getMessage());}catch(Exception ex){System.out.println(ex.getMessage());}}if(item==exit){System.exit(0);}if(item==copy){clipboardstr=this.ta.getSelectedText();}if(item==paste){this.ta.insert(clipboardstr,this.ta.getCaretPosition());}}public static void main(String[]args){NotepadTest note=new NotepadTest();}}


 

原创粉丝点击