|
1 | 1 | package org.eh.core.util; |
2 | 2 |
|
3 | 3 | import java.io.BufferedReader; |
| 4 | +import java.io.File; |
| 5 | +import java.io.FileInputStream; |
4 | 6 | import java.io.IOException; |
5 | 7 | import java.io.InputStream; |
6 | 8 | import java.io.InputStreamReader; |
| 9 | +import java.nio.ByteBuffer; |
| 10 | +import java.nio.channels.FileChannel; |
7 | 11 |
|
8 | 12 | import org.apache.commons.logging.Log; |
9 | 13 | import org.apache.commons.logging.LogFactory; |
@@ -31,4 +35,55 @@ public static String getRequestContent(InputStream inputStream) { |
31 | 35 | } |
32 | 36 | return sb.toString(); |
33 | 37 | } |
| 38 | + |
| 39 | + public static boolean isExist(String path) { |
| 40 | + File file = new File(path); |
| 41 | + return file.exists(); |
| 42 | + } |
| 43 | + |
| 44 | + public static String readFile(String path) { |
| 45 | + if (!isExist(path)) { |
| 46 | + return ""; |
| 47 | + } |
| 48 | + FileInputStream fis = null; |
| 49 | + StringBuilder sb = new StringBuilder(); |
| 50 | + try { |
| 51 | + fis = new FileInputStream(path); |
| 52 | + FileChannel c = fis.getChannel(); |
| 53 | + ByteBuffer bc = ByteBuffer.allocate(1024); |
| 54 | + int i = c.read(bc); |
| 55 | + while (i != -1) { |
| 56 | + sb.append(new String(bc.array())); |
| 57 | + bc.clear(); |
| 58 | + i = c.read(bc); |
| 59 | + } |
| 60 | + c.close(); |
| 61 | + fis.close(); |
| 62 | + } catch (Exception e) { |
| 63 | + log.error("读取模板文件失败:", e); |
| 64 | + } |
| 65 | + return sb.toString(); |
| 66 | + } |
| 67 | + |
| 68 | + public static byte[] readFileByBytes(String path) { |
| 69 | + if (!isExist(path)) { |
| 70 | + return "".getBytes(); |
| 71 | + } |
| 72 | + byte[] bytes = null; |
| 73 | + FileInputStream fis = null; |
| 74 | + try { |
| 75 | + fis = new FileInputStream(path); |
| 76 | + FileChannel c = fis.getChannel(); |
| 77 | + ByteBuffer bc = ByteBuffer.allocate((int) c.size()); |
| 78 | + int i = c.read(bc); |
| 79 | + if (i != -1) { |
| 80 | + bytes = bc.array(); |
| 81 | + } |
| 82 | + c.close(); |
| 83 | + fis.close(); |
| 84 | + } catch (Exception e) { |
| 85 | + log.error("读取资源文件失败:", e); |
| 86 | + } |
| 87 | + return bytes; |
| 88 | + } |
34 | 89 | } |
0 commit comments