Dessa forma o arquivo de destino não é alterado durante a cópia:
- public static void copyFile(File source, File destination) throws IOException {
- if (destination.exists())
- destination.delete();
- FileChannel sourceChannel = null;
- FileChannel destinationChannel = null;
- try {
- sourceChannel = new FileInputStream(source).getChannel();
- destinationChannel = new FileOutputStream(destination).getChannel();
- sourceChannel.transferTo(0, sourceChannel.size(),
- destinationChannel);
- } finally {
- if (sourceChannel != null && sourceChannel.isOpen())
- sourceChannel.close();
- if (destinationChannel != null && destinationChannel.isOpen())
- destinationChannel.close();
- }
- }
Dessa forma o arquivo de destino pode sofrer alterações:
- public class Teste {
- public static void main(String[] args) throws IOException {
- File arquivoOrigem = new File("c:/temp/original.txt");
- FileReader fis = new FileReader(arquivoOrigem);
- BufferedReader bufferedReader = new BufferedReader(fis);
- StringBuilder buffer = new StringBuilder();
- String line = "";
- while ((line = bufferedReader.readLine()) != null) {
- buffer.append(line).append("\n");
- }
- fis.close();
- bufferedReader.close();
- File arquivoDestino = new File("C:/temp/copia.txt");
- FileWriter writer = new FileWriter(arquivoDestino);
- writer.write(buffer.toString());
- writer.flush();
- writer.close();
- }
- }
Nenhum comentário:
Postar um comentário