Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: b87e918a9604ef1aa3dff48ac5b73ebe6f2fa79a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/***************************************************************************
 * Copyright (c) 2004 - 2007 Eike Stepper, Germany.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *    Eike Stepper - initial API and implementation
 **************************************************************************/
package org.eclipse.net4j.util.io;

import org.eclipse.net4j.util.ImplementationError;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * @author Eike Stepper
 */
public final class NIOUtil
{
  private NIOUtil()
  {
  }

  /**
   * TODO Look at {@link #copy(File, File, boolean)}
   */
  public static void copyFile(File source, File target)
  {
    // http://www.javalobby.org/java/forums/t17036.html
    // http://java.sun.com/developer/JDCTechTips/2002/tt0507.html#tip1
    FileChannel sourceChannel = null;
    FileChannel targetChannel = null;

    try
    {
      if (!target.getParentFile().exists())
      {
        target.getParentFile().mkdirs();
      }

      if (!target.exists())
      {
        target.createNewFile();
      }

      sourceChannel = new FileInputStream(source).getChannel();
      targetChannel = new FileOutputStream(target).getChannel();

      long size = sourceChannel.size();
      long transfered = sourceChannel.transferTo(0, size, targetChannel);
      if (transfered != size)
      {
        throw new ImplementationError("Seems as if a loop must be implemented here");
      }
    }
    catch (IOException ex)
    {
      throw new IORuntimeException(ex);
    }
    finally
    {
      IOUtil.closeSilent(sourceChannel);
      IOUtil.closeSilent(targetChannel);
    }
  }

  /**
   * Copy source file to destination. If destination is a path then source file
   * name is appended. If destination file exists then: overwrite=true -
   * destination file is replaced; overwite=false - exception is thrown.
   * 
   * @param src
   *          source file
   * @param dst
   *          destination file or path
   * @param overwrite
   *          overwrite destination file
   * @exception IOException
   *              I/O problem
   * @exception IllegalArgumentException
   *              illegal argument
   */
  @SuppressWarnings("unused")
  private static void copy(final File src, File dst, final boolean overwrite) throws IOException,
      IllegalArgumentException
  {
    long q = System.currentTimeMillis();
    // checks
    if (!src.isFile() || !src.exists())
      throw new IllegalArgumentException("Source file '" + src.getAbsolutePath() + "' not found!");
    if (dst.exists()) if (dst.isDirectory()) // Directory? -> use source file
                                              // name
        dst = new File(dst, src.getName());
      else if (dst.isFile())
      {
        if (!overwrite)
          throw new IllegalArgumentException("Destination file '" + dst.getAbsolutePath() + "' already exists!");
      }
      else
        throw new IllegalArgumentException("Invalid destination object '" + dst.getAbsolutePath() + "'!");
    File dstParent = dst.getParentFile();
    if (!dstParent.exists())
      if (!dstParent.mkdirs()) throw new IOException("Failed to create directory " + dstParent.getAbsolutePath());
    long fileSize = src.length();
    if (fileSize > 20971520l)
    { // for larger files (20Mb) use streams
      FileInputStream in = new FileInputStream(src);
      FileOutputStream out = new FileOutputStream(dst);
      try
      {
        int doneCnt = -1, bufSize = 32768;
        byte buf[] = new byte[bufSize];
        while ((doneCnt = in.read(buf, 0, bufSize)) >= 0)
          if (doneCnt == 0)
            Thread.yield();
          else
            out.write(buf, 0, doneCnt);
        out.flush();
      }
      finally
      {
        try
        {
          in.close();
        }
        catch (IOException e)
        {
        }

        try
        {
          out.close();
        }
        catch (IOException e)
        {
        }
      }
    }
    else
    { // smaller files, use channels
      FileInputStream fis = new FileInputStream(src);
      FileOutputStream fos = new FileOutputStream(dst);
      FileChannel in = fis.getChannel(), out = fos.getChannel();

      try
      {
        long offs = 0, doneCnt = 0, copyCnt = Math.min(65536, fileSize);
        do
        {
          doneCnt = in.transferTo(offs, copyCnt, out);
          offs += doneCnt;
          fileSize -= doneCnt;
        }

        while (fileSize > 0);
      }
      finally
      { // cleanup
        try
        {
          in.close();
        }
        catch (IOException e)
        {
        }

        try
        {
          out.close();
        }
        catch (IOException e)
        {
        }

        try
        {
          fis.close();
        }
        catch (IOException e)
        {
        }

        try
        {
          fos.close();
        }
        catch (IOException e)
        {
        }
      }
    } // else

    System.out.println(">>> " + String.valueOf(src.length() / 1024) + " Kb, "
        + String.valueOf(System.currentTimeMillis() - q));
  } // copy
}

Back to the top