zoukankan      html  css  js  c++  java
  • IO简单示例

    File

    用于对磁盘上的文件或目录进行操作

    直接父类是Object

     

     

    创建一个文件

    public class FileTest

    {

        public static void main(String[] args) throws IOException

        {

           File file = new File("C:/text.txt");

          

           System.out.println(file.createNewFile());

        }

    }

     

    在一个目录下创建文件

    public class FileTest2

    {

        public static void main(String[] args) throws IOException

        {

           File file = new File("C:/abc");

          

           File file2 = new File(file,"hello.txt");

          

           System.out.println(file2.createNewFile());

          

           File file3 = new File(file,"xyz/world.txt");

          

           System.out.println(file3.createNewFile());

        }

    }

     

     

    创建目录操作

    public class FileTest3

    {

        public static void main(String[] args)

        {

           File file = new File("C:/abc/xyz/hello");

          

           System.out.println(file.mkdirs());

          

           System.out.println(file.isDirectory());

        }

    }

     

     

    列出指定目录下的文件或目录

    public class FileTest4

    {

        public static void main(String[] args)

        {

           File file = new File("C:/java");

          

           String[] names  = file.list();

          

           for(String name: names)

           {

               System.out.println(name);

           }

          

           File[] files = file.listFiles();

          

           for(File f : files)

           {

               System.out.println(f.getName());

               System.out.println(f.getParent());

           }

        }

    }

     

     

    文件删除操作

    public class FileTest5

    {

        public static void main(String[] args) throws IOException

        {

           File file = new File("C:/abc/xyz/hello/text.txt");

          

           //file.createNewFile();

          

           boolean delete = file.delete();

          

           System.out.println(delete);

        }

    }

     

     

    文件名过滤操作

    public class FileTest6

    {

        public static void main(String[] args)

        {

           File file = new File("C:/java");

          

           /*String[] names = file.list();

          

           for(String name : names)

           {

               if(name.endsWith(".java"))

               {

                  System.out.println(name);

               }

           }*/

          

           String[] names = file.list(new FilenameFilter()

           {

               @Override

               public boolean accept(File dir, String name)

               {

                  if(name.endsWith(".java"))

                  {

                      return true;

                  }

                  return false;

               }

           });

          

           for(String name : names )

           {

               System.out.println(name);

           }

        }

    }

     

     

    文件分隔符的使用

    public class FileTest7

    {

        public static void main(String[] args) throws IOException

        {

           //不加盘符表示java安装的默认盘

           File file = new File(File.separator + "helo.txt");

          

           System.out.println(file.createNewFile());

        }

    }

     

     

    递归的使用(关键在于要先指定一个出口,才不会出现死循环)

    public class Test1

    {

        public static int calc(int num)

        {

           if(num ==1 )

               return 1;

           else

               return num * calc(num - 1);

        }

     

        public static void main(String[] args)

        {

           System.out.println(calc(5));

        }

    }

     

     

    斐波那契数列

    public class Fabonaci

    {

        public int calc(int pos)

        {

           if(1 == pos || 2 == pos)

               return 1;

           else

               return calc(pos-1)+calc(pos-2);

        }

       

        private void sysout()

        {

           Fabonaci fab = new Fabonaci();

           fab.calc(30);

        }

    }

     

     

    删除指定目录下的所有文件(用递归实现)

    public class FileTest8

    {

        public static void deleteAll(File file)

        {

           if(file.isFile() || 0 == file.list().length)

           {

               file.delete();

           }

           else

           {

               File[] files = file.listFiles();

              

               for(File f : files)

               {

                  deleteAll(f);

                  f.delete();

               }

           }

        }

       

        public static void main(String[] args)

        {

           File file = new File("C:/test");

          

           try

           {

               deleteAll(file);

           }

           catch (Exception e)

           {

               // TODO Auto-generated catch block

               e.printStackTrace();

           }

        }

    }

     

     

     

    把指定目录下的文件结构以树的形式打印出来

    public class FileTest9

    {

        // 判断目录或文件所在的层数

        private static int times;

     

        // 把目录下的文件以树结构的形式打印出来。

        static void treeShow(File file)

        {

           if (file.isFile() || 0 == file.listFiles().length)

           {

               return;

           }

           else

           {

               File[] files = file.listFiles();

     

               files = sortFile(files);

     

               for (File f : files)

               {

                  StringBuffer sb = new StringBuffer();

     

                  if (f.isDirectory())

                  {

                      sb.append(getTAbs(times));

                      sb.append(f.getName());

                      sb.append("\\");

                  }

                  else

                  {

                      sb.append(getTAbs(times));

                      sb.append(f.getName());

                  }

     

                  System.out.println(sb);

     

                  if (f.isDirectory())

                  {

                      times++;

                      treeShow(f);

                      times--;

                  }

               }

           }

        }

     

        // 取得每个目录或文件所处层数的缩进

        private static String getTAbs(int times)

        {

           StringBuffer sb = new StringBuffer();

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

           {

               sb.append("\t");

           }

     

           return sb.toString();

        }

     

        // 把目录下所有文件以目录为先的次序排序

        private static File[] sortFile(File[] files)

        {

           List<File> list = new ArrayList<File>();

           for (File f : files)

           {

               if (f.isDirectory())

               {

                  list.add(f);

               }

           }

           for (File f : files)

           {

               if (f.isFile())

               {

                  list.add(f);

               }

           }

     

           return list.toArray(new File[files.length]);

        }

     

        public static void main(String[] args)

        {

           File file = new File("C:/xdict");

           treeShow(file);

        }

    }

     

     

    Stream

     

    从功能上分:输入流(InputStream)和输出流(OutputStream

    从结构上分:字节流(Byte Streams)和字符流(Character Streams)

     

    字节流输入输出的基础是抽象类InputStreamOutputStream

    字符流输入输出的基础是抽象类ReaderWriter

     

    流的分类:

    节点流:从特定的地方读写的流类。

    过滤流:使用节点流作为输入或输出。过滤流是使用一个已存在的输入流或输出流连接创建的。

    字节流的使用

     

    FileInputStream类的使用

    public class InputStreamTest

    {

        public static void main(String[] args) throws Exception

        {

           InputStream is = new FileInputStream("c:/hello.txt");

     

           byte[] buffer = new byte[200];

     

           int length = 0;

     

           if (-1 != (length = is.read(buffer, 0, 200)))

           {

               String str = new String(buffer, 0, length);

               System.out.println(str);

           }

     

           is.close();

        }

    }

     

    FileOutputStream类的使用

    public class OutputStreamTest

    {

        public static void main(String[] args) throws IOException

        {

           OutputStream os = new FileOutputStream("c:/out.txt",true);

          

           String str = "\nwelcomle";

          

           byte[] buffer = str.getBytes();

          

           os.write(buffer);

          

           os.close();

        }

    }

     

     

    BufferedInputStream类,继承自FilterInputStream

     

     

     

    BufferedOutputStream类,继承自FilterOutputStream

    public class BufferedOutputStreamTest

    {

        public static void main(String[] args) throws Exception

        {

           OutputStream os = new FileOutputStream("1.txt");

          

           BufferedOutputStream bos = new BufferedOutputStream(os);

          

           bos.write("http://www.sina.com.cn".getBytes());

          

           bos.close();

           os.close();

        }

    }

     

     

    ByteArrayInputStream

    public class ByteArrayInputStreamTest

    {

        public static void main(String[] args) throws Exception

        {

           String str = "abcdef";

          

           byte[] byteArr = str.getBytes();

          

           ByteArrayInputStream bais = new ByteArrayInputStream(byteArr);

          

           int c;

          

           //一次只读一个字符

           while(-1 != (c = bais.read()))

           {

               if(0==c)

               {

                  System.out.println((char)c);

               }

               else

               {

                  System.out.println(Character.toUpperCase((char) c));

               }

           }

          

           bais.close();

        }

    }

     

     

    ByteArrayOutputStream

    public class ByteArrayOutputStreamTest

    {

        public static void main(String[] args) throws Exception

        {

           String str = "hello world welcome";

          

           byte[] arr = str.getBytes();

          

           ByteArrayOutputStream baos = new ByteArrayOutputStream();

          

           //把字节数组写入到字节数组输出流中

           baos.write(arr);

          

           //从字节数组输出流中得到字节数组

           byte[] result = baos.toByteArray();

          

           for(byte b : result)

           {

               System.out.println((char)b);

           }

          

           OutputStream os = new FileOutputStream("c:/test.txt");

          

           //把字节数组写入到文件中。

           baos.writeTo(os);

          

           baos.close();

           os.close();

        }

    }

     

     

    DataInputStream类,继承自FilterInputStream

     

     

     

    DataOutputStream类,继承自FilterOutputStream

    public class DataOutputStreamTest

    {

        public static void main(String[] args) throws Exception

        {

           DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data.txt")));

          

           byte b = 3;

           int i = 12;

           char c = 'c';

           float f = 0.3f;

          

           dos.writeByte(b);

           dos.writeInt(i);

           dos.writeChar(c);

           dos.writeFloat(f);

          

           dos.close();

          

           DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("data.txt")));

          

           System.out.println(dis.readByte());

           System.out.println(dis.readInt());

           System.out.println(dis.readChar());

           System.out.println(dis.readFloat());

          

           dis.close();

        }

    }

     

     

     

    自定义一个ByteArrayInputStream

    public class MyOwnStream

    {

        public static void main(String[] args) throws Exception

        {

           byte[] bytes = new byte[16];

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

           {

               bytes[i] = (byte) i;

           }

     

           MyInputStream myis = new MyInputStream(bytes);

     

           int c = 0;

           while (true)

           {

               if (-1 == (c = myis.read()))

               {

                  break;

               }

               System.out.print(c + " ");

           }

     

           myis.close();

        }

    }

     

    // 这里使用了装饰者模式

    class MyInputStream extends InputStream

    {

        protected byte[] buffer;

        protected int ptr = 0;

     

        public MyInputStream(byte[] bytes)

        {

           buffer = bytes;

        }

     

        @Override

        public int read() throws IOException

        {

           return (ptr < buffer.length) ? buffer[ptr++] : -1;

        }

    }

     

    重写InputStream类方法完整的例子

    public class MyOwnStream2 extends InputStream

    {

        protected byte[] data;

        protected int ptr = 0;

        protected int mark = 0;

     

        public MyOwnStream2(byte[] bytes)

        {

           this.data = bytes;

        }

     

        @Override

        public int read() throws IOException

        {

           return (ptr < data.length) ? data[ptr++] : -1;

        }

     

        @Override

        public int read(byte[] b, int off, int len) throws IOException

        {

           if (ptr > data.length || len < 0)

           {

               return -1;

           }

           if ((ptr + len) > data.length)

           {

               len = data.length - ptr;

           }

           if (0 == len)

           {

               return 0;

           }

     

           System.arraycopy(data, ptr, b, off, len);

           ptr += len;

           return len;

        }

     

        @Override

        public long skip(long n) throws IOException

        {

           return super.skip(n);

        }

     

        @Override

        public int available() throws IOException

        {

           return data.length - ptr;

        }

     

        @Override

        public void close() throws IOException

        {

           ptr = data.length;

        }

     

        @Override

        public synchronized void mark(int readlimit)

        {

           this.mark = readlimit;

        }

     

        @Override

        public synchronized void reset() throws IOException

        {

           if (mark > 0 || mark < data.length)

           {

               throw new IOException("The position is invalid.");

           }

     

           ptr = mark;

        }

     

        @Override

        public boolean markSupported()

        {

           return true;

        }

    }

     

     

    字符流的使用

     

    InputStreamReader

     

    OutputStreamWrite

    public class StreamTest

    {

        public static void main(String[] args) throws Exception

        {

           FileOutputStream fos = new FileOutputStream("file.txt");

     

           OutputStreamWriter osw = new OutputStreamWriter(fos);

     

           BufferedWriter bw = new BufferedWriter(osw);

     

           bw.write("http://www.google.com");

           bw.write("\n");

           bw.write("http://www.baidu.com");

     

           bw.close();

     

           FileInputStream fis = new FileInputStream("file.txt");

     

           InputStreamReader isr = new InputStreamReader(fis);

     

           BufferedReader br = new BufferedReader(isr);

     

          

           /*System.out.println(br.readLine());

           System.out.println(br.readLine());

           System.out.println(br.readLine());*/

          

           String str = br.readLine();

           while(null != str)

           {

               System.out.println(str);

               str = br.readLine();

           }

     

           br.close();

        }

    }

     

     

    BufferedReader

    public class StreamTest2

    {

        public static void main(String[] args) throws Exception

        {

           InputStreamReader isr = new InputStreamReader(System.in);

          

           BufferedReader br = new BufferedReader(isr);

          

           String str;

          

           while(null != (str = br.readLine()))

           {

               System.out.println(str);

           }

          

           br.close();

        }

    }

     

    BufferedWrite

    FileOutputStream fos = new FileOutputStream("file.txt");

     

           OutputStreamWriter osw = new OutputStreamWriter(fos);

     

           BufferedWriter bw = new BufferedWriter(osw);

     

           bw.write("http://www.google.com");

           bw.write("\n");

           bw.write("http://www.baidu.com");

     

           bw.close();

     

     

     

    FileReader

    public class FileReaderTest

    {

        public static void main(String[] args) throws Exception

        {

           FileReader fr = new FileReader("src/com/anllin/io3/FileReaderTest.java");

          

           BufferedReader br = new BufferedReader(fr);

           

           String str ;

           while(null != (str = br.readLine()))

           {

               System.out.println(str);

           }

          

           br.close();

        }

    }

     

    FileWriter

    public class FileWriteTest

    {

        public static void main(String[] args) throws Exception

        {

           String str = "hello world welcome nice bueaty";

          

           char[] buffer = new char[str.length()];

          

           str.getChars(0,str.length(),buffer,0);

          

           FileWriter fr = new FileWriter("file2.txt");

          

           fr.write(buffer);

          

           fr.close();

        }

    }

     

     

    CharArrayReader

    public class CharArrayReaderTest

    {

        public static void main(String[] args) throws Exception

        {

           String str = "abcdefghijklmnopqrstuvwxyz";

          

           char[] buffer = new char[str.length()];

          

           str.getChars(0, str.length(),buffer,0);

          

           CharArrayReader car = new CharArrayReader(buffer);

          

           int i ;

          

           while(-1 != (i = car.read()))

           {

               System.out.println((char)i);

           }

          

           car.close();

        }

    }

     

     

    字符集的分类:

    ASCII     GB2312        GBK       Unicode         iso-8859- 1     UTF-8

    public class CharsetTest

    {

        public static void main(String[] args)

        {

           SortedMap<String,Charset> map = Charset.availableCharsets();

          

           Set<String> set = map.keySet();

          

           for(Iterator<String> iter = set.iterator(); iter.hasNext();)

           {

               System.out.println(iter.next());

           }

        }

    }

     

     

    RandomAccessFile类,可以随机对文件进行读写操作。

    public class RandomAccessFileTest

    {

        public static void main(String[] args) throws Exception

        {

           Person p = new Person(1, "anllin", 170);

     

           RandomAccessFile raf = new RandomAccessFile("person.txt", "rw");

     

           p.write(raf);

     

           raf.seek(0);//让读的位置回到文件的开头

     

           Person p2 = new Person();

     

           p2.read(raf);

     

           System.out.println(p2.getId() + ", " + p2.getName() + ", "

                  + p2.getHeight());

        }

    }

     

    class Person

    {

        int id;

        String name;

        double height;

     

        public Person()

        {

     

        }

     

        public Person(int id, String name, double height)

        {

           this.id = id;

           this.name = name;

           this.height = height;

        }

     

        public int getId()

        {

           return id;

        }

     

        public void setId(int id)

        {

           this.id = id;

        }

     

        public String getName()

        {

           return name;

        }

     

        public void setName(String name)

        {

           this.name = name;

        }

     

        public double getHeight()

        {

           return height;

        }

     

        public void setHeight(double height)

        {

           this.height = height;

        }

     

        public void write(RandomAccessFile raf) throws Exception

        {

           raf.writeInt(id);

           raf.writeUTF(name);

           raf.writeDouble(height);

        }

     

        public void read(RandomAccessFile raf) throws Exception

        {

           this.id = raf.readInt();

           this.name = raf.readUTF();

           this.height = raf.readDouble();

        }

    }

     

  • 相关阅读:
    UnQLite简介
    .net中webconfig自定义配置
    webservice有关application/xop+xml的异常
    .NET4缓存过期策略摘录
    关于sea.js的笔记
    npm笔记和bower
    使用npm安装一些包失败了的看过来(npm国内镜像介绍)
    easyui的datagird动态设置当前页数
    Oracle中Merge into用法总结
    Oracle 12.1.0.2 对JSON的支持
  • 原文地址:https://www.cnblogs.com/zfc2201/p/2143648.html
Copyright © 2011-2022 走看看