File I/O

来源:互联网 发布:ewb仿真软件下载 编辑:程序博客网 时间:2024/06/06 03:30

1.    字节流  

public static void main(String[] args) throws IOException {// TODO Auto-generated method stub            File file=new File("E:/S2226.txt");    //创建文件             file.createNewFile();if(file.exists()){System.out.println("存在");           //判断是否存在}long lastModified = file.lastModified();//文件最后一次修改时间    对比时间1970年 1月1日  输出数字为毫秒System.out.println(lastModified);System.out.println(file.length());}

public static void main(String[] args) throws IOException {// TODO Auto-generated method stub    FileInputStream fis=new FileInputStream("E:/S2226.txt");     byte[] bytes=new byte[1024];     int data=fis.read(bytes);     while(data!=-1){     String temp=new String(bytes,0,data);     System.out.println(temp);     data=fis.read(bytes);     }     

    记得关闭流     



输出的效果图 如下:




这里要关闭流.



2.  字符流  


public static void main(String[] args)throws IOException {// TODO Auto-generated method stub//读取文件Reader reader=new FileReader("E:/S2226.txt");BufferedReader bf=new BufferedReader(reader);String line;while ((line=bf.readLine())!=null){System.out.println(line);}bf.close();reader.close();}

public static void main(String[] args)throws IOException {// TODO Auto-generated method stub          Writer writer=new FileWriter("E:/S2226.txt");          BufferedWriter bw=new BufferedWriter(writer);          String words="嗯哼?";          bw.write(words);                    bw.close();          writer.close();                    }


public static void main(String[] args) throws IOException{// TODO Auto-generated method stubInputStream is=new FileInputStream("D:/001.gif");DataInputStream dis=new DataInputStream(is);OutputStream os=new FileOutputStream("E:/002.gif");DataOutputStream dos=new DataOutputStream(os);byte[] bytes=new byte[1024];int data;while((data=dis.read(bytes))!=-1){dos.write(bytes,0,data);}dos.close();os.close();dis.close();is.close();System.out.println("粘贴成功");}




0 0