java IO操作大全

1.对一个文件添加
 try {
        BufferedWriter out = new BufferedWriter(new FileWriter("filename", true));
        out.write("aString");
        out.close();
    } catch (IOException e) {
    }

2.确定两个文件名路径指向同一个文件

 <strong>File file1 = new File("./filename");
    File file2 = new File("filename");
    
    // Filename paths are not equal
    boolean b = file1.equals(file2);      // false
    
    // Normalize the paths
    try {
        file1 = file1.getCanonicalFile(); // c:\almanac1.4\filename
        file2 = file2.getCanonicalFile(); // c:\almanac1.4\filename
    } catch (IOException e) {
    }
    
    // Filename paths are now equal
    b = file1.equals(file2);              // true</strong>


3.创建文件名路径
<strong> String path = File.separator + "a" + File.separator + "b";</strong>

4.copy目录
<strong> public void copyDirectory(File srcDir, File dstDir) throws IOException {
        if (srcDir.isDirectory()) {
            if (!dstDir.exists()) {
                dstDir.mkdir();
            }
    
            String[] children = srcDir.list();
            for (int i=0; i<children.length; i++) {
                copyDirectory(new File(srcDir, children[i]),
                                     new File(dstDir, children[i]));
            }
        } else {
            // This method is implemented in e1071 Copying a File
            copyFile(srcDir, dstDir);
        }
    }
</strong>

5.

文件间拷贝

// Copies src file to dst file.
    // If the dst file does not exist, it is created
    void copy(File src, File dst) throws IOException {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);
    
        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }

6.创建目录

 // Create a directory; all ancestor directories must exist
    boolean success = (new File("directoryName")).mkdir();
    if (!success) {
        // Directory creation failed
    }
    
    // Create a directory; all non-existent ancestor directories are
    // automatically created
    success = (new File("directoryName")).mkdirs();
    if (!success) {
        // Directory creation failed
    }

7.创建文件

<strong>try {
        File file = new File("filename");
    
        // Create file if it does not exist
        boolean success = file.createNewFile();
        if (success) {
            // File did not exist and was created
        } else {
            // File already exists
        }
    } catch (IOException e) {
    }</strong>

8.创建临时文件
 <strong>try {
        // Create temp file.
        File temp = File.createTempFile("pattern", ".suffix");
    
        // Delete temp file when program exits.
        temp.deleteOnExit();
    
        // Write to temp file
        BufferedWriter out = new BufferedWriter(new FileWriter(temp));
        out.write("aString");
        out.close();
    } catch (IOException e) {
    }</strong>


9.获取当前工作路径
<strong>String curDir = System.getProperty("user.dir");</strong>

10.删除一个目录
  // Delete an empty directory
    boolean success = (new File("directoryName")).delete();
    if (!success) {
        // Deletion failed
    }

 // Deletes all files and subdirectories under dir.
    // Returns true if all deletions were successful.
    // If a deletion fails, the method stops attempting to delete and returns false.
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
    
        // The directory is now empty so delete it
        return dir.delete();
    }

11.删除文件
  boolean success = (new File("filename")).delete();
    if (!success) {
        // Deletion failed
    }

12.反序列化一个对象
try {
        // Deserialize from a file
        File file = new File("filename.ser");
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
        // Deserialize the object
        javax.swing.JButton button = (javax.swing.JButton) in.readObject();
        in.close();
    
        // Get some byte array data
        byte[] bytes = getBytesFromFile(file);
        // see e36 将文件读入字节数组 for the implementation of this method
    
        // Deserialize from a byte array
        in = new ObjectInputStream(new ByteArrayInputStream(bytes));
        button = (javax.swing.JButton) in.readObject();
        in.close();
    } catch (ClassNotFoundException e) {
    } catch (IOException e) {
    }

13.实现一个可序列化的Singleton
   public class MySingleton implements Serializable {
        static MySingleton singleton = new MySingleton();
    
        private MySingleton() {
        }
    
        // This method is called immediately after an object of this class is deserialized.
        // This method returns the singleton instance.
        protected Object readResolve() {
            return singleton;
        }
    }

14.确定文件或目录是否存在
boolean exists = (new File("filename")).exists();
    if (exists) {
        // File or directory exists
    } else {
        // File or directory does not exist
    }

15.将文件读入字节数组
public static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);
    
        // Get the size of the file
        long length = file.length();
    
        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }
    
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
    
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }
    
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
    
        // Close the input stream and return bytes
        is.close();
        return bytes;
    }

16.在文件名路径和URL之间转换
 // Create a file object
    File file = new File("filename");
    
    // Convert the file object to a URL
    URL url = null;
    try {
        // The file need not exist. It is made into an absolute path
        // by prefixing the current working directory
        url = file.toURL();          // file:/d:/almanac1.4/java.io/filename
    } catch (MalformedURLException e) {
    }
    
    // Convert the URL to a file object
    file = new File(url.getFile());  // d:/almanac1.4/java.io/filename
    
    // Read the file contents using the URL
    try {
        // Open an input stream
        InputStream is = url.openStream();
    
        // Read from is
    
        is.close();
    } catch (IOException e) {
        // Could not open the file
    }

17.从相对文件名路径获得绝对文件名路径
 File file = new File("filename.txt");
    file = file.getAbsoluteFile();  // c:\temp\filename.txt
    
    file = new File("dir"+File.separatorChar+"filename.txt");
    file = file.getAbsoluteFile();  // c:\temp\dir\filename.txt
    
    file = new File(".."+File.separatorChar+"filename.txt");
    file = file.getAbsoluteFile();  // c:\temp\..\filename.txt
    
    // Note that filename.txt does not need to exist


18.列出目录下文件或者子目录
 File dir = new File("directoryName");
    
    String[] children = dir.list();
    if (children == null) {
        // Either dir does not exist or is not a directory
    } else {
        for (int i=0; i<children.length; i++) {
            // Get filename of file or directory
            String filename = children[i];
        }
    }
    
    // It is also possible to filter the list of returned files.
    // This example does not return any files that start with `.'.
    FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return !name.startsWith(".");
        }
    };
    children = dir.list(filter);
    
    
    // The list of files can also be retrieved as File objects
    File[] files = dir.listFiles();
    
    // This filter only returns directories
    FileFilter fileFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory();
        }
    };
    files = dir.listFiles(fileFilter);





19.得到文件大小
 File file = new File("infilename");
    
    // Get the number of bytes in the file
    long length = file.length();

20.获得一个文件名路径的上一层路径
 // Get the parent of a relative filename path
    File file = new File("Ex1.java");
    String parentPath = file.getParent();      // null
    File parentDir = file.getParentFile();     // null
    
    // Get the parents of an absolute filename path
    file = new File("D:\\almanac\\Ex1.java");
    parentPath = file.getParent();             // D:\almanac
    parentDir = file.getParentFile();          // D:\almanac
    
    parentPath = parentDir.getParent();        // D:\
    parentDir = parentDir.getParentFile();     // D:\
    
    parentPath = parentDir.getParent();        // null
    parentDir = parentDir.getParentFile();     // null

21.确定文件名路径是文件还是目录
File dir = new File("directoryName");
    
    boolean isDir = dir.isDirectory();
    if (isDir) {
        // dir is a directory
    } else {
        // dir is a file
    }

22.获取并设置文件或目录的修改时间
 File dir = new File("directoryName");
    
    String[] children = dir.list();
    if (children == null) {
        // Either dir does not exist or is not a directory
    } else {
        for (int i=0; i<children.length; i++) {
            // Get filename of file or directory
            String filename = children[i];
        }
    }
    
    // It is also possible to filter the list of returned files.
    // This example does not return any files that start with `.'.
    FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return !name.startsWith(".");
        }
    };
    children = dir.list(filter);
    
    
    // The list of files can also be retrieved as File objects
    File[] files = dir.listFiles();
    
    // This filter only returns directories
    FileFilter fileFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory();
        }
    };
    files = dir.listFiles(fileFilter);



23.将文件或目录移动到另外的目录
// File (or directory) to be moved
    File file = new File("filename");
    
    // Destination directory
    File dir = new File("directoryname");
    
    // Move file to new directory
    boolean success = file.renameTo(new File(dir, file.getName()));
    if (!success) {
        // File was not successfully moved
    }

24.标记化java源码
try {
        // Create the tokenizer to read from a file
        FileReader rd = new FileReader("filename.java");
        StreamTokenizer st = new StreamTokenizer(rd);
    
        // Prepare the tokenizer for Java-style tokenizing rules
        st.parseNumbers();
        st.wordChars('_', '_');
        st.eolIsSignificant(true);
    
        // If whitespace is not to be discarded, make this call
        st.ordinaryChars(0, ' ');
    
        // These calls caused comments to be discarded
        st.slashSlashComments(true);
        st.slashStarComments(true);
    
        // Parse the file
        int token = st.nextToken();
        while (token != StreamTokenizer.TT_EOF) {
            token = st.nextToken();
            switch (token) {
            case StreamTokenizer.TT_NUMBER:
                // A number was found; the value is in nval
                double num = st.nval;
                break;
            case StreamTokenizer.TT_WORD:
                // A word was found; the value is in sval
                String word = st.sval;
                break;
            case '"':
                // A double-quoted string was found; sval contains the contents
                String dquoteVal = st.sval;
                break;
            case '\'':
                // A single-quoted string was found; sval contains the contents
                String squoteVal = st.sval;
                break;
            case StreamTokenizer.TT_EOL:
                // End of line character found
                break;
            case StreamTokenizer.TT_EOF:
                // End of file has been reached
                break;
            default:
                // A regular character was found; the value is the token itself
                char ch = (char)st.ttype;
                break;
            }
        }
        rd.close();
    } catch (IOException e) {
    }


25.从标准输入流中获取文本
try {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String str = "";
        while (str != null) {
            System.out.print("> prompt ");
            str = in.readLine();
            process(str);
        }
    } catch (IOException e) {
    }

26.读取UTF-8编码数据
 try {
        BufferedReader in = new BufferedReader(
            new InputStreamReader(new FileInputStream("infilename"), "UTF8"));
        String str = in.readLine();
    } catch (UnsupportedEncodingException e) {
    } catch (IOException e) {
    }

27.读取ISO Latin-1编码数据
 try {
        BufferedReader in = new BufferedReader(
            new InputStreamReader(new FileInputStream("infilename"), "8859_1"));
        String str = in.readLine();
    } catch (UnsupportedEncodingException e) {
    } catch (IOException e) {
    }


28.从文件中获取文本
  try {
        BufferedReader in = new BufferedReader(new FileReader("infilename"));
        String str;
        while ((str = in.readLine()) != null) {
            process(str);
        }
        in.close();
    } catch (IOException e) {
    }

29.重命名文件或目录
 // File (or directory) with old name
    File file = new File("oldname");
    
    // File (or directory) with new name
    File file2 = new File("newname");
    
    // Rename file (or directory)
    boolean success = file.renameTo(file2);
    if (!success) {
        // File was not successfully renamed
    }


30.列出文件系统根目录
 File[] roots = File.listRoots();
    for (int i=0; i<roots.length; i++) {
        process(roots[i]);
    }


31.序列化一个对象
Object object = new javax.swing.JButton("push me");
    
    try {
        // Serialize to a file
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
        out.writeObject(object);
        out.close();
    
        // Serialize to a byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
        out = new ObjectOutputStream(bos) ;
        out.writeObject(object);
        out.close();
    
        // Get the bytes of the serialized object
        byte[] buf = bos.toByteArray();
    } catch (IOException e) {
    }

32.强制文件更新保存到磁盘
try {
        // Open or create the output file
        FileOutputStream os = new FileOutputStream("outfilename");
        FileDescriptor fd = os.getFD();
    
        // Write some data to the stream
        byte[] data = new byte[]{(byte)0xCA, (byte)0xFE, (byte)0xBA, (byte)0xBE};
        os.write(data);
    
        // Flush the data from the streams and writers into system buffers.
        // The data may or may not be written to disk.
        os.flush();
    
        // Block until the system buffers have been written to disk.
        // After this method returns, the data is guaranteed to have
        // been written to disk.
        fd.sync();
    } catch (IOException e) {
    }

33.遍历目录
// Process all files and directories under dir
    public static void visitAllDirsAndFiles(File dir) {
        process(dir);
    
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllDirsAndFiles(new File(dir, children[i]));
            }
        }
    }
    
    // Process only directories under dir
    public static void visitAllDirs(File dir) {
        if (dir.isDirectory()) {
            process(dir);
    
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllDirs(new File(dir, children[i]));
            }
        }
    }
    
    // Process only files under dir
    public static void visitAllFiles(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                visitAllFiles(new File(dir, children[i]));
            }
        } else {
            process(dir);
        }
    }

34.使用随机访问文件
try {
        File f = new File("filename");
        RandomAccessFile raf = new RandomAccessFile(f, "rw");
    
        // Read a character
        char ch = raf.readChar();
    
        // Seek to end of file
        raf.seek(f.length());
    
        // Append to the end
        raf.writeChars("aString");
        raf.close();
    } catch (IOException e) {
    }


35.写入ISO Latin-1编码数据
 try {
        Writer out = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream("outfilename"), "8859_1"));
        out.write(aString);
        out.close();
    } catch (UnsupportedEncodingException e) {
    } catch (IOException e) {
    }

36.写入一个文件
try {
        BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
        out.write("aString");
        out.close();
    } catch (IOException e) {
    }

37.写入UTF-8编码数据
 try {
        Writer out = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream("outfilename"), "UTF8"));
        out.write(aString);
        out.close();
    } catch (UnsupportedEncodingException e) {
    } catch (IOException e) {
    }






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值