文件IO的几种方式

记录:对于文件IO操作方法的,后期可以用于数据驱动测试自动化中的针对文件用例或者Excel用户参数的读取、写入执行

  1 public class FileTest {
  2 
  3     /**
  4      * 在当前目录下创建文件
  5      *
  6      * @param fileName
  7      */
  8     public void createFile(String fileName) {
  9         try {
 10             String currentFilePath = FileTest.class.getResource("/").toURI().getPath();
 11             String pathFileName = currentFilePath + "\" + fileName;
 12             File file = new File(pathFileName);
 13             boolean bRet = file.createNewFile();
 14             if (bRet) {
 15                 System.out.println(pathFileName + "--新文件创建成功");
 16             } else {
 17                 System.out.println(pathFileName + "--新文件创建失败");
 18             }
 19         } catch (Exception e) {
 20             e.printStackTrace();
 21         }
 22     }
 23 
 24     /**
 25      * 根据指定的目录,查询当前目录下的所有子目录名
 26      *
 27      * @param dirName     路径名
 28      * @param allFileName 所有文件的名称
 29      */
 30 
 31     public void getDirAllFileName(String dirName, List<String> allFileName) {
 32         if (dirName != null && allFileName != null) {
 33             File file = new File(dirName);
 34             if (file.exists()) {
 35                 File[] files = file.listFiles();
 36                 for (File f : files) {
 37                     if (f.isDirectory()) {
 38                         String subPath = f.getPath();             //获得子目录的文件名
 39                         getDirAllFileName(subPath, allFileName);      //递归
 40                     } else {
 41                         allFileName.add(dirName + "------" + f.getName());
 42                     }
 43                 }
 44             }
 45         } else {
 46             System.out.println("入参为null");
 47         }
 48     }
 49 
 50     /**
 51      * 读取文件,返回文件对应的字节数组
 52      *
 53      * @param fileName
 54      * @return
 55      */
 56     public List<Byte> readFile(String fileName) {
 57         List<Byte> bytes = new ArrayList<Byte>(1024 * 100);
 58         File file = new File(fileName);
 59         try {
 60             FileInputStream fileInputStream = new FileInputStream(file);
 61             FileOutputStream outputStream = new FileOutputStream("F:\stream1.jpg");
 62             byte[] bs = new byte[1024];
 63             int iCount;
 64             while ((iCount = fileInputStream.read(bs)) != -1) {
 65                 for (Byte bt : bs) {
 66                     bytes.add(bt);
 67                 }
 68                 outputStream.write(bs);                 //一次写一个缓冲区的数据
 69             }
 70             fileInputStream.close();    //关闭字节流
 71             outputStream.close();
 72         } catch (Exception e) {
 73             e.printStackTrace();
 74         }
 75         return bytes;
 76     }
 77 
 78     /**
 79      * 把字节流数组写入指定的文件中
 80      *
 81      * @param bytes
 82      * @param pathFileName
 83      * @throws Exception
 84      */
 85     public void writeFile(List<Byte> bytes, String pathFileName) throws Exception {
 86         if (bytes != null && pathFileName != null) {
 87             File file = new File(pathFileName);
 88             try {
 89                 FileOutputStream fileOutputStream = new FileOutputStream(file);
 90                 byte[] bt = new byte[bytes.size()];
 91                 for (int i = 0; i < bytes.size(); i++) {
 92                     bt[i] = bytes.get(i);
 93                 }
 94                 fileOutputStream.write(bt);
 95                 fileOutputStream.close();
 96             } catch (Exception e) {
 97                 e.printStackTrace();
 98             }
 99         }
100     }
101 
102     /**
103      * 读取文本文件
104      *
105      * @param fileName
106      * @return
107      */
108     public String readTextFile(String fileName) {
109         StringBuilder builder = new StringBuilder();
110         if (fileName != null) {
111             BufferedReader in = null;
112             try {
113                 in = new BufferedReader(new FileReader(fileName));     //用缓存提高效率
114                 String str;
115                 while ((str = in.readLine()) != null) {
116                     builder.append(str);
117                     System.out.println(str);
118                 }
119             } catch (Exception e) {
120                 e.printStackTrace();
121             } finally {
122                 if (in != null) {
123                     try {
124                         in.close();
125                     } catch (Exception e) {
126                         e.printStackTrace();
127                     }
128                 }
129             }
130         }
131 
132         return builder.toString();
133     }
134 }

相应的测试类:

public class TestReader {
    public static void main(String[] args) {
        FileTest fileTest = new FileTest();
        String strRet = fileTest.readTextFile("F:\aa.txt");
    }
}
public class TestRecursive {
    public static void main(String[] args) {
        FileTest fileTest = new FileTest();
        String dirName = "D:\WorkSpace";
        List<String> allFileName = new ArrayList<String>(200);
        fileTest.getDirAllFileName(dirName, allFileName);
        for (String filename : allFileName) {
            System.out.println(filename);
        }
        System.out.println("一共有:" + allFileName.size() + "文件");
    }
}
public class TestStream {
    public static void main(String[] args){
        FileTest fileTest = new FileTest();
        String file  = "F:\stream.jpg";
        List<Byte> bytes =  fileTest.readFile("F:\t0132e5ce657c0702ac.jpg");
        System.out.println("文件大小:"+ bytes.size());
  /*      try{
            fileTest.writeFile(bytes,file);
            System.out.println(file+"复制成功");
        }catch (Exception e){
            e.printStackTrace();
        }*/

    }
}

写了个Log类,用于不使用Log4j时的轻量化处理

 1 public class Log {
 2     public static void writeError(String strSource, String errMsg) {
 3         PrintWriter out = null;
 4         try {
 5             String path = Log.class.getResource("/").toURI().getPath();
 6             String pathFileName = path + "\" + "errlog";
 7             File file = new File(pathFileName);
 8             if (!file.exists()) {
 9                 file.createNewFile();
10             }
11             out = new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
12             SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
13             out.println(sd.format(new Date()));
14             out.println(strSource);
15             out.println(errMsg);
16             out.println("");
17         } catch (Exception e) {
18             e.printStackTrace();
19         } finally {
20             if (out != null) {
21                 try {
22                     out.close();
23                 } catch (Exception e) {
24                     e.printStackTrace();
25                 }
26             }
27         }
28     }
29 }

相关测试:

public class TestLog {
    public static void main(String[] args){
        Log.writeError("FileTest-->>readTxtFile","数据库连接失败");
        Log.writeError("FileTest-->>writeFile","连接中断");
        Log.writeError("FileTest-->>readFile","IO错误");
    }
}
原文地址:https://www.cnblogs.com/drnmmond/p/7611499.html