1 18 19 package com.Ostermiller.util; 20 21 import java.io.*; 22 import java.text.MessageFormat ; 23 import java.util.ResourceBundle ; 24 import java.util.Locale ; 25 26 34 public class FileHelper { 35 36 41 protected static ResourceBundle labels = ResourceBundle.getBundle("com.Ostermiller.util.FileHelper", Locale.getDefault()); 42 43 44 56 public static void move(File from, File to) throws IOException { 57 move(from, to, false); 58 } 59 60 71 public static void move(File from, File to, boolean overwrite) throws IOException { 72 if (to.exists()){ 73 if (overwrite){ 74 if (!to.delete()){ 75 throw new IOException( 76 MessageFormat.format( 77 labels.getString("deleteerror"), 78 (Object [])new String [] { 79 to.toString() 80 } 81 ) 82 ); 83 } 84 } else { 85 throw new IOException( 86 MessageFormat.format( 87 labels.getString("alreadyexistserror"), 88 (Object [])new String [] { 89 to.toString() 90 } 91 ) 92 ); 93 } 94 } 95 96 if (from.renameTo(to)) return; 97 98 InputStream in = null; 99 OutputStream out = null; 100 try { 101 in = new FileInputStream(from); 102 out = new FileOutputStream(to); 103 copy(in, out); 104 in.close(); 105 in = null; 106 out.flush(); 107 out.close(); 108 out = null; 109 if (!from.delete()){ 110 throw new IOException( 111 MessageFormat.format( 112 labels.getString("deleteoriginalerror"), 113 (Object [])new String [] { 114 from.toString(), 115 to.toString() 116 } 117 ) 118 ); 119 } 120 } finally { 121 if (in != null){ 122 in.close(); 123 in = null; 124 } 125 if (out != null){ 126 out.flush(); 127 out.close(); 128 out = null; 129 } 130 } 131 } 132 133 138 private final static int BUFFER_SIZE = 1024; 139 140 149 private static void copy(InputStream in, OutputStream out) throws IOException { 150 byte[] buffer = new byte[BUFFER_SIZE]; 151 int read; 152 while((read = in.read(buffer)) != -1){ 153 out.write(buffer, 0, read); 154 } 155 } 156 } 157 | Popular Tags |