|
| 1 | +package com.cloud.utils; |
| 2 | + |
| 3 | +import java.io.BufferedInputStream; |
| 4 | +import java.io.BufferedWriter; |
| 5 | +import java.io.File; |
| 6 | +import java.io.FileInputStream; |
| 7 | +import java.io.FileOutputStream; |
| 8 | +import java.io.FileWriter; |
| 9 | +import java.io.IOException; |
| 10 | +import java.io.InputStream; |
| 11 | +import java.io.OutputStream; |
| 12 | + |
| 13 | +public class FileUtil { |
| 14 | + |
| 15 | + public static String readFileAsString(String filePath) { |
| 16 | + File file = new File(filePath); |
| 17 | + if(!file.exists()) |
| 18 | + return null; |
| 19 | + |
| 20 | + try { |
| 21 | + byte[] buffer = new byte[(int)file.length()]; |
| 22 | + BufferedInputStream f = null; |
| 23 | + try { |
| 24 | + f = new BufferedInputStream(new FileInputStream(filePath)); |
| 25 | + f.read(buffer); |
| 26 | + } finally { |
| 27 | + if (f != null) { |
| 28 | + try { |
| 29 | + f.close(); |
| 30 | + } catch (IOException ignored) { |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + return new String(buffer); |
| 35 | + } catch(IOException e) { |
| 36 | + return null; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public static void writeToFile(String content, String filePath) throws IOException { |
| 41 | + BufferedWriter out = null; |
| 42 | + try { |
| 43 | + out = new BufferedWriter(new FileWriter(filePath)); |
| 44 | + out.write(content); |
| 45 | + } finally { |
| 46 | + if(out != null) |
| 47 | + out.close(); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public static void copyfile(File f1, File f2) throws IOException { |
| 52 | + InputStream in = new FileInputStream(f1); |
| 53 | + OutputStream out = new FileOutputStream(f2); |
| 54 | + |
| 55 | + try { |
| 56 | + byte[] buf = new byte[1024]; |
| 57 | + int len; |
| 58 | + while ((len = in.read(buf)) > 0) { |
| 59 | + out.write(buf, 0, len); |
| 60 | + } |
| 61 | + } finally { |
| 62 | + in.close(); |
| 63 | + out.close(); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
0 commit comments