文件读写

     由于是第二次读,从第九章开始,同时,只记录了一些,以前不是很熟的地方。

这里只是用于备份

     第九章:

        1,File对象有一个重要但又容易忽视的特点,就是它具有不变性(immutable.

        2,File.separator File.separatorChar。作用相同。

        3,关于路径方面

            UNC(Universal Naming Convention)用于提供一种与机器无关的识别网络上共享资源的路径的方法。

            Windows环境下

                  //servername/directory_path/filename

            windows环境下

                  //servername/directory_path/filename

        4,访问系统属性

            测试了一下user.home

           System.out.print(System.getProperty("user.home")); // C:/Documents and Settings/chandler

            System.clearPropertySystem.setProperty

        5.文件筛选
          
如果要用列举文件名有两种方法,一种是list()返回的是String数组,包括文件名,另一个是listFiles(),返回的是file对象数组
           list
()方法,要实现FilenameFilter接口
           listFiles()f
方法,要实现Filefilter接口。

           代码

 /*过滤器类,这个类只要实现accept方法就好,

     这个类的作用实际上就是把以name开头,同时扩展名为extension的文件筛选出来

*/

import java.io.File;

import java.io.FilenameFilter;

public class FileListFilter implements FilenameFilter {

  private String name;        // File name filter

  private String extension;   // File extension filter

 

  // Constructor

  public FileListFilter(String name, String extension) {

    this.name = name;                                                       //用来过滤的类的名字

    this.extension = extension;                                           //扩展名

  }

 

  public boolean accept(File directory, String filename) {

    boolean fileOK = true;

 

    // If there is a name filter specified, check the file name

    if (name != null) {                                                               

      fileOK &= filename.startsWith(name);                           //筛选起始名   

    }

 

    // If there is an extension filter, check the file extension

    if (extension != null) {

      fileOK &= filename.endsWith('.' + extension);               //筛选扩展名

    }

 

    return fileOK;

  }

}

 

使用类

import java.io.File;

import java.io.FilenameFilter;

import java.util.Date;                 // For the Date class

 

public class TryFile3 {

  public static void main(String[] args) {

 

    // Create an object that is a directory

    File myDir = new File("C:/j2sdk1.5.0/src/java/io");

    System.out.println(myDir.getAbsolutePath() 

                       + (myDir.isDirectory() ? " is " : " is not ")

                       + "a directory");

    System.out.println("The parent of " + myDir.getName() + " is "

                       + myDir.getParent());

 

    // Define a filter for java source files beginning with F

    FilenameFilter select = new FileListFilter("F", "java");

 

    // Get the contents of the directory

    File[] contents = myDir.listFiles(select);                    //开始吧筛选器放入筛选中

 

    // List the contents

    if (contents != null) {

      System.out.println("/nThe " + contents.length

                         + " matching items in the directory, "

                         + myDir.getName() + ", are:");

      for (File file : contents) {

        System.out.println(file + " is a " 

                   + (file.isDirectory() ? "directory" : "file")

                   + " last modified on/n" 

                   + new Date(file.lastModified()));

    }

    } else {

      System.out.println(myDir.getName() + " is not a directory");

    } 

 

    return;

  }

}

        6.不熟悉的文件处理办法

           这里最好看api来学习

           就一个createTempFile()创建零时文件,返回一个File对象

           deleteOnExit() 再程序退出时,删除文件。
 
   第十章,写文件

    1,缓冲区的Limitposition

       position:指下一个将要读取或写入的缓冲区元素的索引位置

       limit:      第一个不能读取或写入的值的索引位置

 System.out.println("buf's position:"+buf.position());

 System.out.println("buf's limit:"+buf.limit());

 System.out.println("buf's capacity:"+buf.capacity());

       结果

        buf's position:0

        buf's limit:1024

        buf's capacity:1024

    

  2 视图缓冲区

      基本来说就是建立一个单独的ByteBuffer,然后用用其asXXXbuffer来建立。

      因为生成的缓冲区,其没有自己独立的内存来存放数据。把数据放入视图缓冲区中的,实际上也是放入ByteBuffer中。

      但是很不好的一点就是如果往视图缓冲区中放入数据,原本的ByteBufferlimitpositon并不会跟着改变。所以来说呢,如果手动改,

      例子

       ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);

 

    DoubleBuffer doubleBuf = buf.asDoubleBuffer();

    buf.position(8);

    CharBuffer charBuf = buf.asCharBuffer();

    LongBuffer longBuf = null;

    String primeStr = null;

 

    for (long prime : primes) {

          primeStr = "prime = " + prime;             // Create the string

          doubleBuf.put(0,(double)primeStr.length()); // Store the string length

          charBuf.put(primeStr);                     // Store the string

          buf.position(2*charBuf.position() + 8);    // Position for 3rd buffer

          longBuf = buf.asLongBuffer();              // Create the buffer

          longBuf.put(prime);                        // Store the binary long value

          buf.position(buf.position() + 8);          // Set position after last value

          buf.flip();                                // and flip

      try {

            file.write(buf);                         // Write the buffer as before.

      } catch (IOException e) {

            e.printStackTrace(System.err);

            System.exit(1);

      } 

      buf.clear();

      doubleBuf.clear();

      charBuf.clear();

    } 

         

利用本地的字符集

     写入文件不会出现比较怪异的字符

 import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.FileNotFoundException;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

 

public class WriteAStringAsBytes {

  public static void main(String[] args) {

 

    String phrase = new String("Garbage in, garbage out/n");

    String dirname = "C:/Beg Java Stuff";        // Directory name

    String filename = "byteData.txt";

 

    File aFile = new File(dirname, filename);

 

    // Create the file output stream

    FileOutputStream file = null;

    try {

      file = new FileOutputStream(aFile, true);

    } catch (FileNotFoundException e) {

      e.printStackTrace(System.err);

    } 

    FileChannel outChannel = file.getChannel();

    ByteBuffer buf = ByteBuffer.allocate(phrase.length());

    byte[] bytes = phrase.getBytes();

    buf.put(bytes);

    buf.flip();

 

    try {

      outChannel.write(buf);

     file.close();                    // Close the output stream & the channel

    } catch (IOException e) {

      e.printStackTrace(System.err);

    }

  }

}

 

使用formatter对象装载缓冲区

   这一块,其实我也不是十分清楚。感觉是再formatter调用formatter方法时,就把

   ByteBuffer buf = ByteBuffer.allocate(1024);

    System.out.println("/nByte buffer:");

    System.out.printf("position = %2d  Limit = %4d  capacity = %4d%n",

                             buf.position(), buf.limit(), buf.capacity());

 

    // Create a view buffer

    CharBuffer charBuf = buf.asCharBuffer();

    System.out.println("Char view buffer:");

    System.out.printf("position = %2d  Limit = %4d  capacity = %4d%n",

                            charBuf.position(),charBuf.limit(),charBuf.capacity());

    Formatter formatter = new Formatter(charBuf);

 

    // Write to the view buffer using a formatter

    int number = 0;                    // Proverb number

    for(String phrase : phrases) {    

      formatter.format("%nProverb%3d: %s", ++number, phrase);

      System.out.println("/nView buffer after loading:");

      System.out.printf("position = %2d  Limit = %4d  capacity = %4d%n",

                             charBuf.position(), charBuf.limit(),charBuf.capacity());

      charBuf.flip();                        // Flip the view buffer

      System.out.println("View buffer after flip:");

      System.out.printf("position = %2d  Limit = %4d  length = %4d%n",

                      charBuf.position(),charBuf.limit(),charBuf.length());

      buf.limit(2*charBuf.length());        // Set byte buffer limit

 

      System.out.println("Byte buffer after limit update:");

      System.out.printf("position = %2d  Limit = %4d  length = %4d%n",

                              buf.position(),buf.limit(), buf.remaining());

 

      // Write the file

      try {

        outChannel.write(buf);                // Write the buffer to the file channel

        System.out.println("Buffer contents written to file.");

        buf.clear();

        charBuf.clear();

      } catch (IOException e) {

       e.printStackTrace(System.err);

       System.exit(1);

      }

    }

    try {

      outputFile.close();                   // Close the O/P stream & the channel

    } catch (IOException e) {

       e.printStackTrace(System.err);

    }

  }

 

  集中写和读

      就是几个buffer同时写入一个channel

     import static java.lang.Math.ceil;  

import static java.lang.Math.sqrt;  

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.FileNotFoundException;

import java.nio.ByteBuffer;

import java.nio.LongBuffer;

import java.nio.DoubleBuffer;

import java.nio.CharBuffer;

import java.nio.channels.FileChannel;

 

public class GatheringWrite {

  public static void main(String[] args) {

    int primesRequired = 100;   // Default count

    if (args.length > 0) {

      try {

        primesRequired = Integer.valueOf(args[0]).intValue();

      } catch (NumberFormatException e) {

        System.out.println("Prime count value invalid. Using default of "

                           + primesRequired);

      }

    } 

 

    long[] primes = new long[primesRequired];    // Array to store primes

    primes[0] = 2;                               // Seed the first prime

    primes[1] = 3;                               // and the second

    // Count of primes found - up to now, which is also the array index

    int count = 2;

    long number = 5;                             // Next integer to be tested

 

    outer:

    for (; count < primesRequired; number += 2) {

 

      // The maximum divisor we need to try is square root of number

      long limit = (long)ceil(sqrt((double) number));

 

      // Divide by all the primes we have up to limit

      for (int i = 1; i < count && primes[i] <= limit; i++) {

        if (number % primes[i] == 0) {           // Is it an exact divisor?

          continue outer;                        // yes, try the next number

 

        }

      }

      primes[count++] = number;                  // We got one!

    }

 

    File aFile = new File("C:/Beg Java Stuff/primes2.txt");  // Different file!

    FileOutputStream outputFile = null;

    try {

      outputFile = new FileOutputStream(aFile);

    } catch (FileNotFoundException e) {

      e.printStackTrace(System.err);

      System.exit(1);

    }

    FileChannel file = outputFile.getChannel();

 

    ByteBuffer[] buffers = new ByteBuffer[3];    // Array of buffer references

    buffers[0] = ByteBuffer.allocate(8);         // To hold a double value

    buffers[2] = ByteBuffer.allocate(8);         // To hold a long value

 

    String primeStr = null;

    for (long prime : primes) {

      primeStr = "prime = " + prime;

      buffers[0].putDouble((double) primeStr.length()).flip();

      buffers[1] = ByteBuffer.allocate(primeStr.length());

      buffers[1].put(primeStr.getBytes()).flip();

      buffers[2].putLong(prime).flip();

      try {

        file.write(buffers);

      } catch (IOException e) {

        e.printStackTrace(System.err);

        System.exit(1);

      } 

      buffers[0].clear();

      buffers[2].clear();

    }

 

    try {

      System.out.println("File written is " + file.size() + " bytes.");

      outputFile.close();                        // Close the file and its channel

    } catch (IOException e) {

      e.printStackTrace(System.err);

      System.exit(1);

    }

 

    System.out.println("File closed");

    System.exit(0);

  }

}

 

  第十一章 读文件

   1,读取混合数据

      这个的目的不是说明什么,而是演示一下大致的读写

      import java.io.FileInputStream;

import java.io.IOException;

import java.io.File;

import java.io.FileNotFoundException;

 

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

 

public class ReadPrimesMixedData {

  public static void main(String[] args) {

    File aFile = new File("C:/Beg Java Stuff/primes.txt");

    FileInputStream inFile = null;

   

    try {

      inFile = new FileInputStream(aFile); 

 

    } catch(FileNotFoundException e) {

      e.printStackTrace(System.err);

      System.exit(1);

    }

  

    FileChannel inChannel = inFile.getChannel();    

    try {

      ByteBuffer lengthBuf = ByteBuffer.allocate(8);

      int strLength = 0;            // Stores the string length 

      ByteBuffer buf = null;        // Stores a reference to the second byte buffer 

      byte[] strChars = null;       // A reference to an array to hold the string

 

      while(true) {

        if(inChannel.read(lengthBuf) == -1)  // Read the string length, 

          break;                             // if its EOF exit the loop

 

        lengthBuf.flip();

 

        // Extract the length and convert to int

        strLength = (int)lengthBuf.getDouble();

 

        // Buffer for the string & the prime

        buf = ByteBuffer.allocate(2*strLength+8);

 

        if(inChannel.read(buf) == -1) {   // Read the string & binary prime value

          assert false;                   // Should not get here!

          break;                          // Exit loop on EOF

        }

        buf.flip();

 

        // First version of code to extract the string       

        strChars = new byte[2*strLength]; // Create the array for the string

        buf.get(strChars);                // Extract string

          

        System.out.printf("String length: %3s  String: %-12s  Binary Value: %3d%n",

                   strLength, ByteBuffer.wrap(strChars).asCharBuffer(),buf.getLong());

 

/*

        // First alternative for extracting the string 

        char[] str = new char[strLength]; // Array to hold the string

        buf.asCharBuffer().get(str);

        System.out.printf("String length: %3s  String: %-12s  Binary Value: %3d%n",

              strLength, new String(str), ((ByteBuffer)(buf.position(2*strLength))).getLong());

*/

        

/*

        // Second alternative for extracting the string 

        char[] str = new char[strLength]; // Array to hold the string

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

          str[i] = buf.getChar();

        }

        System.out.printf("String length: %3s  String: %-12s  Binary Value: %3d%n",

                                     strLength, new String(str), buf.getLong());

*/        

 

        lengthBuf.clear();                // Clear the buffer for the next read

      }

 

      System.out.println("/nEOF reached.");

      inFile.close();                     // Close the file and the channel

 

    } catch(IOException e) {

      e.printStackTrace(System.err);

      System.exit(1);

    }

    System.exit(0);

  }

}

 

 2 压缩缓冲区

    while(true) {

        if(buf.remaining() < 8) {      // Verify enough bytes for string length

          if(inChannel.read(buf.compact()) == -1)  

            break;                                       

          buf.flip();

         }

         strLength = (int)buf.getDouble();

         

         // Verify enough bytes for complete string

         if(buf.remaining()<2*strLength) { 

           if(inChannel.read(buf.compact()) == -1)  

             break;                                       

           buf.flip();

        }

        strChars = new byte[2*strLength];

        buf.get(strChars);

        

        if(buf.remaining()<8) {        // Verify enough bytes for prime value

          if(inChannel.read(buf.compact()) == -1)  

            break;                                       

          buf.flip();

        }

 

        System.out.printf("String length: %3s  String: %-12s  Binary Value: %3d%n",

                   strLength, ByteBuffer.wrap(strChars).asCharBuffer(),buf.getLong());

      }

      System.out.println("/nEOF reached.");

      inFile.close();                   // Close the file and the channel

 

    } catch(IOException e) {

      e.printStackTrace(System.err);

      System.exit(1);

    }

       

 3 通过一个文件通道读写

       File MyPrimes = new File(path);

       RandomAccessFile primesFile = null;

       try{

            primesFile = new RandomAccessFile(myPrimes,"rw");

       }catch{

           e.printStackTrace(System.err);

           assert false

       }

       FileChannel ioChannel=primesFile.getChannel()

4,内存映像文件

        import java.io.File;

import java.io.RandomAccessFile;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.nio.MappedByteBuffer;

import java.nio.channels.FileChannel;

import static java.nio.channels.FileChannel.MapMode.READ_WRITE;

 

public class MemoryMappedFile {

  public static void main(String[] args) {

    File aFile = new File("C:/Beg Java Stuff/primes_backup.bin");

    RandomAccessFile ioFile = null;

    try {

      ioFile = new RandomAccessFile(aFile,"rw");

    } catch(FileNotFoundException e) {

      e.printStackTrace(System.err);

      System.exit(1);

    }

    FileChannel ioChannel = ioFile.getChannel();

    final int PRIMESREQUIRED = 10;

    long[] primes = new long[PRIMESREQUIRED];

 

    int index = 0;                               // Position for a prime in the file

    final long REPLACEMENT = 999999L;            // Replacement for a selected prime

 

    try {

      final int PRIMECOUNT = (int)ioChannel.size()/8;

      MappedByteBuffer buf = ioChannel.map(READ_WRITE, 0L, ioChannel.size()).load();

      ioChannel.close();                         // Close the channel

      for(int i = 0 ; i<PRIMESREQUIRED ; i++) {

        index = 8*(int)(PRIMECOUNT*Math.random());    

        primes[i] = buf.getLong(index);

        buf.putLong(index, REPLACEMENT);

      }

      int count = 0;                             // Count of primes written                    

      for(long prime : primes) {

        System.out.printf("%12d", prime);

        if(++count%5 == 0) {

          System.out.println();

        }

      }

      ioFile.close();                            // Close the file and the channel

    } catch(IOException e) {

      e.printStackTrace(System.err);

      System.exit(1);

    }

      System.exit(0);

  }

}

5,锁定文件

        try {

      int primesRead = 0;

      FileLock inLock = null;

 

      // File reading loop

      while(true) {

        int tryLockCount = 0;

 

        // Loop to get a lock on the file region we want to read

        while(true) {

          inLock = inChannel.tryLock(inChannel.position(), 

                                     buf.remaining(), 

                                     true);

          if(inLock != null) {                   // If we have a lock

           System.out.println("/nAcquired file lock.");

           break;                               // exit the loop

          }

 

          if(++tryLockCount>=100) {              // If we've tried too often

            System.out.printf("Failed to acquire lock after %d tries. Terminating...",

                                               tryLockCount);

            System.exit(1);                      // end the program

          }

 

          // Wait 200 msec before the next try for a file lock 

          try {

                Thread.sleep(200);                    // Wait for 200 milliseconds

          } catch(InterruptedException e) {

              e.printStackTrace(System.err);

          }

        }

 

        // We have a lock so now read the file

        if(inChannel.read(buf) == -1) {

          break;

        }

        inLock.release();                        // Release lock as read is finished

        System.out.println("Released file lock.");

          

        LongBuffer longBuf = ((ByteBuffer)(buf.flip())).asLongBuffer();

        primesRead = longBuf.remaining();

        longBuf.get(primes,0, longBuf.remaining());

        for(int i = 0 ; i< primesRead ; i++) {

          if(i%6 == 0) {

            System.out.println();

          }

          System.out.printf("%12d", primes[i]);

        }

        buf.clear();                             // Clear the buffer for the next read

      }

 

      System.out.println("/nEOF reached.");

      inFile.close();                            // Close the file and the channel

 

    } catch(IOException e) {

      e.printStackTrace(System.err);

      System.exit(1);

    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值