爪哇国新游记之三十三----目录文件操作

简介:

1.判断路径是文件还是目录

复制代码
File subDir=new File("c:\\mp3");
if(subDir.isDirectory()){
   // 是目录
}

File mp3=new File("c:\\mp3\\avemaria.mp3");
                    
if(mp3.isFile()){
   // 是文件
}
复制代码

2.列出目录下的文件和子目录

复制代码
File dir = new File(fromDir);
String[] children = dir.list();

for (int i=0; i<children.length; i++) {
    String filename = children[i];
    ...
}
复制代码

3.文件拷贝

复制代码
public static void copyFile(File sourceFile, File targetFile) throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

            // 新建文件输出流并对它进行缓冲
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        } finally {
            // 关闭流
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    }
复制代码

2016年8月26日23:39:27改版

复制代码
/**
     * 将文件上传到服务器,返回在服务器的路径文件名
     * @param in
     * @param filename
     * @return
     * @throws Exception
     */
    public String upload2Server(InputStream in, String filename) throws Exception {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(in);

            // 新建文件输出流并对它进行缓冲
            String filePathname=uploadPath+getTimePrefix()+filename;
            outBuff = new BufferedOutputStream(new FileOutputStream(new File(filePathname)));

            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
            
            return filePathname;
        } catch(Exception ex){
            logger.error(ex);
            throw ex;
        }
        finally {
            // 关闭流
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    }
复制代码

 

 

4.取得操作系统的临时目录

String folder=System.getProperty("java.io.tmpdir");

 











本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/xiandedanteng/p/4195966.html,如需转载请自行联系原作者


相关文章
|
3月前
|
前端开发 Java
今年十八,喜欢CTF-杂项
今年十八,喜欢CTF-杂项
24 1
我为什么而工作? 文/江湖一剑客
文/江湖一剑客 今天我们来讲一下工作的意义,以及工作、生活、人生的意义等相关话题。 首先,我们来想一个问题:你觉得人的一生该怎样度过呢? 你是想在悲伤苦痛中度过一生,还是想快乐地度过一生呢? 毫无疑问地,人性都是趋吉避凶,追求快乐幸福,挣脱苦痛的。
1505 0