Source Code Cross Referenced for FileUtil.java in  » Source-Control » sourcejammer » org » sourcejammer » util » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Source Control » sourcejammer » org.sourcejammer.util 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         *  Copyright (C) 2001, 2002 Robert MacGrogan
003:         *
004:         *  This library is free software; you can redistribute it and/or
005:         *  modify it under the terms of the GNU Lesser General Public
006:         *  License as published by the Free Software Foundation; either
007:         *  version 2.1 of the License, or (at your option) any later version.
008:         *
009:         *  This library is distributed in the hope that it will be useful,
010:         *  but WITHOUT ANY WARRANTY; without even the implied warranty of
011:         *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012:         *  Lesser General Public License for more details.
013:         *
014:         *  You should have received a copy of the GNU Lesser General Public
015:         *  License along with this library; if not, write to the Free Software
016:         *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
017:         *
018:         *
019:         * $Archive: SourceJammer$
020:         * $FileName: FileUtil.java$
021:         * $FileID: 4305$
022:         *
023:         * Last change:
024:         * $AuthorName: Rob MacGrogan$
025:         * $Date: 8/1/03 7:15 PM$
026:         * $Comment: Just changed main method for testing purposes.$
027:         */
028:
029:        package org.sourcejammer.util;
030:
031:        import java.io.*;
032:        import java.nio.ByteBuffer;
033:        import java.nio.channels.ByteChannel;
034:        import java.nio.channels.Channel;
035:        import java.nio.channels.FileChannel;
036:        import java.util.Enumeration;
037:        import java.util.Properties;
038:
039:        import javax.activation.DataHandler;
040:        import javax.activation.DataSource;
041:        import javax.activation.FileDataSource;
042:
043:        /**
044:         * Title: $FileName: FileUtil.java$
045:         * @author $AuthorName: Rob MacGrogan$
046:         * @version $VerNum: 4$<br><br>
047:         * 
048:         * $Description: $
049:         * $KeyWordsOff: $<br>
050:         */
051:        public class FileUtil {
052:
053:            private static final int BUFFER_SIZE = 102400;
054:
055:            private FileUtil() {
056:            }
057:
058:            public static void sendBytesToSendBytesDataSource(
059:                    SendBytesDataSource source, byte[] by) throws IOException {
060:                ByteArrayInputStream stmIn = new ByteArrayInputStream(by);
061:                try {
062:                    OutputStream stmOut = source.getOutputStream();
063:                    try {
064:                        inputStreamToOutputStream(stmIn, stmOut);
065:                    } finally {
066:                        stmOut.close();
067:                    }
068:                } finally {
069:                    stmIn.close();
070:                }
071:            }
072:
073:            /**
074:             * Saves byte array as a file using fullPathAndName as location.
075:             */
076:            public static void writeBytesToFileSys(byte[] file,
077:                    String fullPathAndName) throws IOException {
078:                File fileWrite = new File(fullPathAndName);
079:                writeBytesToFileSys(file, fileWrite);
080:            }
081:
082:            /**
083:             * Saves byte array as a file using fullPathAndName as location.
084:             */
085:            public static void writeBytesToFileSys(byte[] file, File fileWrite)
086:                    throws IOException {
087:                FileOutputStream stmFileOut = new FileOutputStream(fileWrite);
088:                try {
089:                    stmFileOut.write(file);
090:                    stmFileOut.flush();
091:                } finally {
092:                    stmFileOut.close();
093:                }
094:            }
095:
096:            public static byte[] readBytesFromFileSys(String fullPathAndName)
097:                    throws IOException {
098:                File fileRead = new File(fullPathAndName);
099:                return readBytesFromFileSys(fileRead);
100:            }
101:
102:            private static void channelToOutputStream(ByteChannel channel,
103:                    OutputStream outputStream) throws IOException {
104:                ByteBuffer buff = ByteBuffer.allocate(BUFFER_SIZE);
105:                boolean keepReading = true;
106:                while (keepReading) {
107:                    int ret = channel.read(buff);
108:                    if (ret == -1) {
109:                        keepReading = false;
110:                    } else {
111:                        byte[] bytes = new byte[ret];
112:                        buff.flip();
113:                        buff.get(bytes);
114:                        outputStream.write(bytes);
115:                        buff.clear();
116:                        if (ret < BUFFER_SIZE) {
117:                            keepReading = false;
118:                        }
119:                    }
120:                }
121:            }
122:
123:            public static byte[] newReadBytesFromFileSys(File fileRead)
124:                    throws IOException {
125:                FileInputStream oFileIn = new FileInputStream(fileRead);
126:                ByteArrayOutputStream oByOut = new ByteArrayOutputStream();
127:                ProcessTimer.getDefaultInstance().beginProcess("get channel");
128:                FileChannel channel = oFileIn.getChannel();
129:                ProcessTimer.getDefaultInstance().endProcess("get channel");
130:                ProcessTimer.getDefaultInstance().beginProcess("stream");
131:                channelToOutputStream(channel, oByOut);
132:                ProcessTimer.getDefaultInstance().endProcess("stream");
133:                byte[] rtn = oByOut.toByteArray();
134:                oByOut.close();
135:                channel.close();
136:                oFileIn.close();
137:                return rtn;
138:            }
139:
140:            public static byte[] readBytesFromFileSys(File fileRead)
141:                    throws IOException {
142:
143:                FileInputStream oFileIn = new FileInputStream(fileRead);
144:                ByteArrayOutputStream oByOut = new ByteArrayOutputStream();
145:                byte[] byFile = null;
146:                byte[] buffer = null;
147:                int iBufferSize = BUFFER_SIZE;
148:                try {
149:                    boolean bKeepReadingBytes = true;
150:                    while (bKeepReadingBytes) {
151:                        buffer = new byte[iBufferSize];
152:                        int iBytes = oFileIn.read(buffer);
153:                        if (iBytes == -1) {
154:                            bKeepReadingBytes = false;
155:                        } else {
156:                            oByOut.write(buffer, 0, iBytes);
157:                            if (iBytes < iBufferSize) {
158:                                bKeepReadingBytes = false;
159:                            }
160:                        }//end else bytes != -1
161:                    }//end while
162:                    byFile = oByOut.toByteArray();
163:                }//end try
164:                finally {
165:                    oByOut.close();
166:                    oFileIn.close();
167:                }
168:                return byFile;
169:            }
170:
171:            /**
172:             * Gets an object from file system.
173:             */
174:            public static Object readObjectFromFileSys(String fullPathAndName)
175:                    throws IOException {
176:                File fileRead = new File(fullPathAndName);
177:                return readObjectFromFileSys(fileRead);
178:            }
179:
180:            /**
181:             * Writes the object to the specified location on the
182:             * file system. If the file already exists, it will be overwritten.
183:             */
184:            public static void writeObjectToFileSys(Object o,
185:                    String fullPathAndName) throws IOException {
186:                File fileWrite = new File(fullPathAndName);
187:                writeObjectToFileSys(o, fileWrite);
188:            }
189:
190:            /**
191:             * Writes the object to the specified location on the
192:             * file system. If the file already exists, it will be overwritten.
193:             */
194:            public static void writeObjectToFileSys(Object o, File fileWrite)
195:                    throws IOException {
196:
197:                FileOutputStream stmFileOut = new FileOutputStream(fileWrite);
198:                try {
199:                    ObjectOutputStream stmObjOut = new ObjectOutputStream(
200:                            stmFileOut);
201:                    try {
202:                        stmObjOut.writeObject(o);
203:                        stmObjOut.flush();
204:                    } finally {
205:                        stmObjOut.close();
206:                    }
207:                } finally {
208:                    stmFileOut.close();
209:                }
210:
211:            }
212:
213:            /**
214:             * Gets an object from file system.
215:             */
216:            public static Object readObjectFromFileSys(File fileRead)
217:                    throws IOException {
218:
219:                Object obj = null;
220:
221:                FileInputStream stmFileIn = new FileInputStream(fileRead);
222:                try {
223:                    ObjectInputStream stmObjIn = new ObjectInputStream(
224:                            stmFileIn);
225:                    try {
226:                        obj = stmObjIn.readObject();
227:                    } catch (ClassNotFoundException ex) {
228:                        throw new ConfigurationException(
229:                                "Could not find an object in the specified file.",
230:                                ex);
231:                    } finally {
232:                        stmObjIn.close();
233:                    }
234:                } finally {
235:                    stmFileIn.close();
236:                }
237:
238:                return obj;
239:
240:            }
241:
242:            public static void inputStreamToOutputStream(InputStream stmIn,
243:                    OutputStream stmOut) throws IOException {
244:
245:                byte[] buffer = null;
246:                int iBufferSize = BUFFER_SIZE;
247:                buffer = new byte[iBufferSize];
248:
249:                boolean bKeepStreaming = true;
250:                while (bKeepStreaming) {
251:                    int iBytes = stmIn.read(buffer);
252:                    if (iBytes == -1) {
253:                        bKeepStreaming = false;
254:                    } else {
255:                        if (iBytes < iBufferSize) {
256:                            bKeepStreaming = false;
257:                        }
258:                        stmOut.write(buffer, 0, iBytes);
259:                    }//end else some bytes returned.
260:                }//end while
261:            }
262:
263:            public static void streamFileToFile(File source, File target)
264:                    throws IOException {
265:                handlerStreamFileToFile(source, target);
266:            }
267:
268:            public static void oldStreamFileToFile(File source, File target)
269:                    throws IOException {
270:                FileInputStream stmIn = new FileInputStream(source);
271:                FileOutputStream stmOut = new FileOutputStream(target);
272:                int iBufferSize = BUFFER_SIZE;
273:
274:                inputStreamToOutputStream(stmIn, stmOut);
275:
276:                stmIn.close();
277:                stmOut.close();
278:                target.setLastModified(source.lastModified());
279:            }
280:
281:            public static void simpleStreamFileToFile(File source, File target)
282:                    throws IOException {
283:                FileInputStream stmIn = new FileInputStream(source);
284:                try {
285:                    byte[] b = new byte[stmIn.available()];
286:                    FileOutputStream stmOut = new FileOutputStream(target);
287:                    try {
288:                        stmIn.read(b);
289:                        stmOut.write(b);
290:                        stmOut.flush();
291:                    } finally {
292:                        stmOut.close();
293:                    }
294:                } finally {
295:                    stmIn.close();
296:                }
297:            }
298:
299:            public static void handlerStreamFileToFile(File source, File target)
300:                    throws IOException {
301:                FileOutputStream stmOut = new FileOutputStream(target);
302:                try {
303:                    handlerStreamFileToOutputStream(source, stmOut);
304:                } finally {
305:                    stmOut.close();
306:                }
307:                target.setLastModified(source.lastModified());
308:            }
309:
310:            public static void handlerStreamFileToOutputStream(File source,
311:                    OutputStream target) throws IOException {
312:                FileDataSource dataSource = new FileDataSource(source);
313:                DataHandler handler = new DataHandler(dataSource);
314:                handler.writeTo(target);
315:            }
316:
317:            public static void optStreamFileToFile(File source, File target)
318:                    throws IOException {
319:                if (source.length() > 20480) {
320:                    handlerStreamFileToFile(source, target);
321:                } else {
322:                    simpleStreamFileToFile(source, target);
323:                }
324:            }
325:
326:            public static void newStreamFileToFile(File source, File target)
327:                    throws IOException {
328:                FileOutputStream targetStr = new FileOutputStream(target);
329:                FileInputStream sourceStr = new FileInputStream(source);
330:
331:                FileChannel targetCh = targetStr.getChannel();
332:                FileChannel sourceCh = sourceStr.getChannel();
333:
334:                ByteBuffer buff = ByteBuffer.allocate(BUFFER_SIZE);
335:
336:                while (true) {
337:                    int ret = sourceCh.read(buff);
338:                    if (ret == -1) {
339:                        break;
340:                    } else {
341:                        buff.flip();
342:                        targetCh.write(buff);
343:                        buff.clear();
344:                    }
345:                }
346:                targetCh.close();
347:                sourceCh.close();
348:                targetStr.close();
349:                sourceStr.close();
350:                target.setLastModified(source.lastModified());
351:            }
352:
353:            /**
354:             * Copied from HistoryTypeMapper in cient.
355:             */
356:            public static String getExtension(String fileName) {
357:                String ext = null;
358:                int iDotLocation = fileName.lastIndexOf(".");
359:                if (iDotLocation >= 0) {
360:                    ext = fileName.substring(iDotLocation + 1);
361:                }
362:                return ext;
363:            }
364:
365:            /**
366:             * Move the specified file from sourceDir to targetDir.
367:             */
368:            public static File moveFile(String fileName, File sourceDir,
369:                    File targetDir) throws IOException {
370:                return moveFile(fileName, sourceDir, targetDir, true);
371:            }
372:
373:            /**
374:             * Move the specified file from sourceDir to targetDir. Throws IOException if
375:             * oerwrite is true and target file already exists.
376:             */
377:            public static File moveFile(String fileName, File sourceDir,
378:                    File targetDir, boolean overwrite) throws IOException {
379:                File target = copyFile(fileName, sourceDir, targetDir,
380:                        overwrite);
381:                File source = new File(sourceDir, fileName);
382:                source.delete();
383:                return target;
384:            }
385:
386:            /**
387:             * Move a directory and all its contents.
388:             */
389:            public static void moveDirectory(File sourceDir, File targetDir)
390:                    throws IOException {
391:                copyDirectory(sourceDir, targetDir, true);
392:            }
393:
394:            /**
395:             * Recursively copy a directory.
396:             */
397:            public static void copyDirectory(File sourceDir, File targetDir)
398:                    throws IOException {
399:                copyDirectory(sourceDir, targetDir, false);
400:            }
401:
402:            /**
403:             * Move a directory and all its contents.
404:             */
405:            public static void moveDirectory(File sourceDir, File targetDir,
406:                    Spinner spinner) throws IOException {
407:                copyDirectory(sourceDir, targetDir, true, spinner);
408:            }
409:
410:            /**
411:             * Recursively copy a directory.
412:             */
413:            public static void copyDirectory(File sourceDir, File targetDir,
414:                    Spinner spinner) throws IOException {
415:                copyDirectory(sourceDir, targetDir, false, spinner);
416:            }
417:
418:            /**
419:             * Recursively copy a directory.
420:             */
421:            private static void copyDirectory(File sourceDir, File targetDir,
422:                    boolean isMove) throws IOException {
423:                copyDirectory(sourceDir, targetDir, isMove, null);
424:            }
425:
426:            /**
427:             * Recursively copy a directory.
428:             */
429:            private static void copyDirectory(File sourceDir, File targetDir,
430:                    boolean isMove, Spinner spinner) throws IOException {
431:                //First create the empty directory if it does not exist.
432:                targetDir.mkdirs();
433:
434:                //Now loop through children.
435:                File[] sourceChildren = sourceDir.listFiles();
436:                for (int i = 0; i < sourceChildren.length; i++) {
437:                    File fl = sourceChildren[i];
438:                    if (fl.isDirectory()) {
439:                        File childTarget = new File(targetDir, fl.getName());
440:                        copyDirectory(fl, childTarget, isMove, spinner);
441:                    } else if (fl.isFile()) {
442:                        if (!isMove) {
443:                            copyFile(fl.getName(), sourceDir, targetDir);
444:                        } else {
445:                            moveFile(fl.getName(), sourceDir, targetDir);
446:                        }
447:                    }
448:                    if (spinner != null) {
449:                        spinner.spin();
450:                    }
451:                }
452:                if (isMove) {
453:                    //delete the dir.
454:                    sourceDir.delete();
455:                }
456:            }
457:
458:            /**
459:             * Copy the specified file from sourceDir to targetDir.
460:             */
461:            public static File copyFile(String fileName, File sourceDir,
462:                    File targetDir) throws IOException {
463:                return copyFile(fileName, sourceDir, targetDir, true);
464:            }
465:
466:            /**
467:             * Copy the specified file from sourceDir to targetDir. Throws IOException if
468:             * oerwrite is true and target file already exists.
469:             */
470:            public static File copyFile(String fileName, File sourceDir,
471:                    File targetDir, boolean overwrite) throws IOException {
472:                File source = new File(sourceDir, fileName);
473:                if (!source.exists()) {
474:                    throw new IOException("The file " + source
475:                            + " does not exist.");
476:                }
477:
478:                if (!targetDir.exists() || !targetDir.isDirectory()) {
479:                    throw new IOException("The directory " + targetDir
480:                            + " does not exist.");
481:                }
482:
483:                if (sourceDir.equals(targetDir)) {
484:                    throw new IOException(
485:                            "The source and target files are the same.");
486:                }
487:
488:                File target = new File(targetDir, fileName);
489:                if (!overwrite && target.exists()) {
490:                    throw new IOException("The file " + target
491:                            + " already exists.");
492:                }
493:
494:                FileUtil.streamFileToFile(source, target);
495:                return target;
496:            }
497:
498:            /**
499:             * Copied from com.jj.javadiff.BinaryHandler, part of the javadiff
500:             * package available from Launch Software (www.launchsoftware.com).
501:             */
502:            public static boolean isBinaryFile(File the_file) {
503:                FileInputStream is = null;
504:                try {
505:                    byte[] bytes_buffer = new byte[1024];
506:                    is = new FileInputStream(the_file);
507:                    int bytesRead = is.read(bytes_buffer, 0, 1024);
508:                    if (bytesRead == -1) {
509:                        return false;
510:                    }
511:                    for (int i = 0; i != bytesRead; i++) {
512:                        if (bytes_buffer[i] < 0) {
513:                            return true;
514:                        }
515:                    }
516:                } catch (Exception e) {
517:                    return false;
518:                } finally {
519:                    try {
520:                        is.close();
521:                    } catch (Exception exception) {
522:                        /* empty */
523:                    }
524:                }
525:                return false;
526:            }
527:
528:            public static void main(String[] args) {
529:                try {
530:
531:                    Properties props = System.getProperties();
532:                    Enumeration enm = props.keys();
533:                    while (enm.hasMoreElements()) {
534:                        String key = (String) enm.nextElement();
535:                        System.out.println(key + ": " + props.getProperty(key));
536:                    }
537:
538:                } catch (Throwable thr) {
539:                    thr.printStackTrace();
540:                }
541:            }
542:
543:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.