文件操作

文件操作

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

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 block e.printStackTrace(); } } }


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

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

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

文件操作类

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

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

publicFile(Stringpath,Stringname);根据parent路径名字符串和child路径名字符串创建一个新File对象

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

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

Source.txt

Backup\source.txt

执行备份:

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

其他方法

(1)访问文件对象

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

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

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

l publicStringgetParent()//返回父文件对象的路径名

l publicFilegetParentFile()//返回父文件对象

(2)获得文件属性

l publiclonglength() //返回指定文件的字节长度

l publicbooleanexists()//测试指定的文件是否存在

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

(3)文件操作

l publicbooleanrenameTo(Filedest)//文件重命名

l publicbooleandelete()//删除空目录

(4)目录操作

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

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

l publicFile[]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 stub File f1,f2,dest; //在当前目录中创建文件对象 f1,dest f1 = new File(fname); dest = new File(destdir); if(f1.exists()){ //dest不存在时创建目录 if(!dest.exists()){ System.out.println("dest不存在,创建backup"); dest.mkdir(); } //在目录dest中创建文件f2 f2=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 stub SimpleDateFormat 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(); } }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值