├── .gitignore ├── .idea ├── .gitignore ├── description.html ├── encodings.xml ├── misc.xml ├── modules.xml ├── project-template.xml ├── uiDesigner.xml └── vcs.xml ├── FileManager.iml ├── README.md ├── example.png └── src ├── com └── cyyself │ └── FileManager │ ├── FileItem.java │ ├── FileListPane.java │ ├── Main.java │ ├── toolBar.java │ └── toolBarMenu.java └── org └── apache └── commons └── io ├── ByteOrderMark.java ├── ByteOrderParser.java ├── Charsets.java ├── CopyUtils.java ├── DirectoryWalker.java ├── EndianUtils.java ├── FileCleaner.java ├── FileCleaningTracker.java ├── FileDeleteStrategy.java ├── FileExistsException.java ├── FileSystemUtils.java ├── FileUtils.java ├── FilenameUtils.java ├── HexDump.java ├── IOCase.java ├── IOExceptionWithCause.java ├── IOUtils.java ├── LineIterator.java ├── TaggedIOException.java ├── ThreadMonitor.java ├── comparator ├── AbstractFileComparator.java ├── CompositeFileComparator.java ├── DefaultFileComparator.java ├── DirectoryFileComparator.java ├── ExtensionFileComparator.java ├── LastModifiedFileComparator.java ├── NameFileComparator.java ├── PathFileComparator.java ├── ReverseComparator.java ├── SizeFileComparator.java └── package.html ├── filefilter ├── AbstractFileFilter.java ├── AgeFileFilter.java ├── AndFileFilter.java ├── CanReadFileFilter.java ├── CanWriteFileFilter.java ├── ConditionalFileFilter.java ├── DelegateFileFilter.java ├── DirectoryFileFilter.java ├── EmptyFileFilter.java ├── FalseFileFilter.java ├── FileFileFilter.java ├── FileFilterUtils.java ├── HiddenFileFilter.java ├── IOFileFilter.java ├── MagicNumberFileFilter.java ├── NameFileFilter.java ├── NotFileFilter.java ├── OrFileFilter.java ├── PrefixFileFilter.java ├── RegexFileFilter.java ├── SizeFileFilter.java ├── SuffixFileFilter.java ├── TrueFileFilter.java ├── WildcardFileFilter.java ├── WildcardFilter.java └── package.html ├── input ├── AutoCloseInputStream.java ├── BOMInputStream.java ├── BoundedInputStream.java ├── BoundedReader.java ├── BrokenInputStream.java ├── CharSequenceInputStream.java ├── CharSequenceReader.java ├── ClassLoaderObjectInputStream.java ├── CloseShieldInputStream.java ├── ClosedInputStream.java ├── CountingInputStream.java ├── DemuxInputStream.java ├── InfiniteCircularInputStream.java ├── MessageDigestCalculatingInputStream.java ├── NullInputStream.java ├── NullReader.java ├── ObservableInputStream.java ├── ProxyInputStream.java ├── ProxyReader.java ├── ReaderInputStream.java ├── ReversedLinesFileReader.java ├── SwappedDataInputStream.java ├── TaggedInputStream.java ├── Tailer.java ├── TailerListener.java ├── TailerListenerAdapter.java ├── TeeInputStream.java ├── UnixLineEndingInputStream.java ├── WindowsLineEndingInputStream.java ├── XmlStreamReader.java ├── XmlStreamReaderException.java └── package.html ├── monitor ├── FileAlterationListener.java ├── FileAlterationListenerAdaptor.java ├── FileAlterationMonitor.java ├── FileAlterationObserver.java ├── FileEntry.java └── package.html ├── output ├── AppendableOutputStream.java ├── BrokenOutputStream.java ├── ByteArrayOutputStream.java ├── ChunkedOutputStream.java ├── ChunkedWriter.java ├── CloseShieldOutputStream.java ├── ClosedOutputStream.java ├── CountingOutputStream.java ├── DeferredFileOutputStream.java ├── DemuxOutputStream.java ├── FileWriterWithEncoding.java ├── LockableFileWriter.java ├── NullOutputStream.java ├── NullWriter.java ├── ProxyOutputStream.java ├── ProxyWriter.java ├── StringBuilderWriter.java ├── TaggedOutputStream.java ├── TeeOutputStream.java ├── ThresholdingOutputStream.java ├── WriterOutputStream.java ├── XmlStreamWriter.java └── package.html ├── overview.html ├── package.html └── serialization ├── ClassNameMatcher.java ├── FullClassNameMatcher.java ├── RegexpClassNameMatcher.java ├── ValidatingObjectInputStream.java ├── WildcardClassNameMatcher.java └── package.html /.gitignore: -------------------------------------------------------------------------------- 1 | out/ 2 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /.idea/description.html: -------------------------------------------------------------------------------- 1 | Simple Java application that includes a class with main() method -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/project-template.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /FileManager.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Simple File Manger 2 | 3 | ~~这是一个使用Java编写的文件管理器。~~ 4 | 5 | 有点丢人的学校大作业。 6 | 7 | ## 实验目的 8 | 运用面向对象程序设计思想,基于Java文件管理和I/O框架,实现基于图形界面的GUI文件管理器。 9 | 10 | ## 实验项目内容 11 | 1. [x] 实现文件夹创建、删除、进入。 12 | 2. [x] 实现当前文件夹下的内容罗列。 13 | 3. [x] 实现文件拷贝和文件夹拷贝(文件夹拷贝指深度拷贝,包括所有子目录和文件)。 14 | 4. [x] 实现指定文件的加密和解密。 15 | 5. [x] 实现指定文件和文件夹的压缩。 16 | 6. [x] 实现压缩文件的解压。 17 | 7. [x] 文件管理器具有图形界面。 18 | 19 | ![example](example.png) 20 | -------------------------------------------------------------------------------- /example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyyself/SimpleFileManager/4ea830af184182991087379585026a0e9de245e5/example.png -------------------------------------------------------------------------------- /src/com/cyyself/FileManager/FileItem.java: -------------------------------------------------------------------------------- 1 | package com.cyyself.FileManager; 2 | 3 | import javax.swing.tree.DefaultMutableTreeNode; 4 | import java.io.File; 5 | 6 | class FileItem extends DefaultMutableTreeNode { 7 | public File file; 8 | FileItem(File newFile) { 9 | super(newFile.getName()); 10 | file = newFile; 11 | if (file.isDirectory()) { 12 | add(new DefaultMutableTreeNode("")); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /src/com/cyyself/FileManager/FileListPane.java: -------------------------------------------------------------------------------- 1 | package com.cyyself.FileManager; 2 | 3 | import javax.swing.*; 4 | import javax.swing.event.*; 5 | import javax.swing.tree.*; 6 | import java.awt.*; 7 | import java.awt.event.*; 8 | import java.io.File; 9 | import java.io.IOException; 10 | 11 | class FileListPane extends JScrollPane { 12 | public JTree tree; 13 | public toolBarMenu menu = new toolBarMenu(); 14 | FileListPane(File dir) { 15 | cd(dir); 16 | } 17 | void cd(File dir) { 18 | DefaultMutableTreeNode top = new DefaultMutableTreeNode(dir.getAbsolutePath()); 19 | for (File x:dir.listFiles()) { 20 | top.add(new FileItem(x)); 21 | } 22 | tree = new JTree(top); 23 | tree.setRootVisible(false); 24 | JScrollPane that = this; 25 | tree.addTreeExpansionListener(new TreeExpansionListener() { 26 | @Override 27 | public void treeExpanded(TreeExpansionEvent treeExpansionEvent) { 28 | MainFrame.reDirectTo(getSelectedPath()); 29 | } 30 | @Override 31 | public void treeCollapsed(TreeExpansionEvent treeExpansionEvent) { 32 | 33 | } 34 | }); 35 | tree.addMouseListener(new MouseListener() { 36 | @Override 37 | public void mouseClicked(MouseEvent mouseEvent) { 38 | if (SwingUtilities.isRightMouseButton(mouseEvent)) { 39 | boolean selected = MainFrame.dirView.tree.getSelectionPath() != null; 40 | menu.open.setEnabled(selected); 41 | menu.cut.setEnabled(selected); 42 | menu.copy.setEnabled(selected); 43 | menu.delete.setEnabled(selected); 44 | menu.paste.setEnabled(!menu.copyFrom.isEmpty()); 45 | menu.encrypt.setEnabled(false); 46 | menu.decrypt.setEnabled(false); 47 | menu.unzip.setEnabled(false); 48 | menu.zip.setEnabled(false); 49 | if (selected) { 50 | menu.zip.setEnabled(true); 51 | File selFile = new File(getSelectedPath()); 52 | String filename = selFile.getName(); 53 | if (selFile.isFile()) { 54 | String format = filename.substring(filename.lastIndexOf(".")); 55 | if (format.equals(".encrypted")) menu.decrypt.setEnabled(true); 56 | else menu.encrypt.setEnabled(true); 57 | if (format.equals(".zip")) menu.unzip.setEnabled(true); 58 | } 59 | } 60 | menu.show(tree,mouseEvent.getX(),mouseEvent.getY()); 61 | } 62 | else if (SwingUtilities.isLeftMouseButton(mouseEvent) && mouseEvent.getClickCount() == 2) { 63 | File sel = new File(MainFrame.dirView.getSelectedPath()); 64 | if (sel.isFile()) { 65 | try { 66 | Desktop.getDesktop().open(sel); 67 | } catch (IOException e) { 68 | e.printStackTrace(); 69 | System.out.println("打开失败"); 70 | } 71 | } 72 | } 73 | } 74 | 75 | @Override 76 | public void mousePressed(MouseEvent mouseEvent) { 77 | 78 | } 79 | 80 | @Override 81 | public void mouseReleased(MouseEvent mouseEvent) { 82 | 83 | } 84 | 85 | @Override 86 | public void mouseEntered(MouseEvent mouseEvent) { 87 | 88 | } 89 | 90 | @Override 91 | public void mouseExited(MouseEvent mouseEvent) { 92 | 93 | } 94 | }); 95 | setViewportView(tree); 96 | } 97 | String getSelectedPath() { 98 | TreePath tp = MainFrame.dirView.tree.getSelectionPath(); 99 | if (tp == null) return ""; 100 | String filename = tp.getLastPathComponent().toString(); 101 | if (filename != null && !filename.isEmpty()) { 102 | String newPath = MainFrame.cur_Folder.getAbsolutePath() + File.separator + filename; 103 | return newPath; 104 | } 105 | return ""; 106 | } 107 | } -------------------------------------------------------------------------------- /src/com/cyyself/FileManager/Main.java: -------------------------------------------------------------------------------- 1 | package com.cyyself.FileManager; 2 | 3 | 4 | import javax.swing.*; 5 | import java.awt.*; 6 | import java.io.*; 7 | import java.util.ArrayList; 8 | 9 | class MainFrame extends JFrame{ 10 | static File cur_Folder = new File(System.getProperty("user.dir")); 11 | static toolBar topBar = new toolBar(cur_Folder.getAbsolutePath()); 12 | static FileListPane dirView = new FileListPane(cur_Folder); 13 | static ArrayList history = new ArrayList(); 14 | static int history_idx = 0; 15 | public static boolean ChangeDirection(File new_direction) { 16 | if (new_direction.isDirectory()) { 17 | cur_Folder = new_direction; 18 | topBar.path_text.setText(cur_Folder.getAbsolutePath()); 19 | dirView.cd(cur_Folder); 20 | topBar.back_button.setEnabled(history_idx > 0); 21 | topBar.forward_button.setEnabled(history_idx < history.size() - 1); 22 | return true; 23 | } 24 | else { 25 | topBar.path_text.setText(cur_Folder.getAbsolutePath()); 26 | System.out.println("ERROR: new_direction is not a directory."); 27 | return false; 28 | } 29 | } 30 | public static boolean reDirectTo(String newPath) { 31 | while (history.size() > history_idx + 1) { 32 | history.remove(history.size() - 1); 33 | } 34 | File newFile = new File(newPath); 35 | if (newFile.isDirectory()) { 36 | history.add(newFile.getAbsolutePath()); 37 | history_idx++; 38 | ChangeDirection(newFile); 39 | return true; 40 | } 41 | return false; 42 | } 43 | public MainFrame() { 44 | setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 45 | setLayout(new BorderLayout()); 46 | add(topBar, BorderLayout.NORTH); 47 | add(dirView, BorderLayout.CENTER); 48 | history.add(cur_Folder.getAbsolutePath()); 49 | topBar.setRootFrame(this); 50 | } 51 | public static void main(String[] args) { 52 | MainFrame fm = new MainFrame(); 53 | fm.setTitle("文件管理器"); 54 | fm.setSize(800, 480); 55 | fm.setVisible(true); 56 | } 57 | } 58 | 59 | 60 | -------------------------------------------------------------------------------- /src/com/cyyself/FileManager/toolBar.java: -------------------------------------------------------------------------------- 1 | package com.cyyself.FileManager; 2 | 3 | import javax.swing.*; 4 | import java.awt.*; 5 | import java.awt.event.*; 6 | import java.io.File; 7 | 8 | class toolBar extends JPanel { 9 | public Button back_button = new Button("<"); 10 | public Button forward_button = new Button(">"); 11 | public Button ancestor_button = new Button("^"); 12 | public Button cd_button = new Button("Browse"); 13 | public JPanel button_group = new JPanel(); 14 | public JTextField path_text; 15 | public JFrame rootFrame; 16 | public void setRootFrame(JFrame root) { 17 | rootFrame = root; 18 | } 19 | public toolBar(String path) { 20 | path_text = new JTextField(path); 21 | path_text.addActionListener(new ActionListener() { 22 | @Override 23 | public void actionPerformed(ActionEvent actionEvent) { 24 | MainFrame.ChangeDirection(new File(path_text.getText())); 25 | } 26 | }); 27 | back_button.setEnabled(false); 28 | forward_button.setEnabled(false); 29 | ancestor_button.addActionListener(new ActionListener() { 30 | @Override 31 | public void actionPerformed(ActionEvent actionEvent) { 32 | String separator = File.separator; 33 | if (separator.equals("\\")) separator = "\\\\"; 34 | String[] path = MainFrame.cur_Folder.getAbsolutePath().toString().split(separator); 35 | StringBuilder newPath = new StringBuilder(); 36 | for (int i=0;i 38 | * Returns {@code ByteOrder.LITTLE_ENDIAN} if the given value is {@code "LITTLE_ENDIAN"}. 39 | *

40 | *

41 | * Returns {@code ByteOrder.BIG_ENDIAN} if the given value is {@code "BIG_ENDIAN"}. 42 | *

43 | * Examples: 44 | *
    45 | *
  • {@code ByteOrderParser.parseByteOrder("LITTLE_ENDIAN")} returns {@code ByteOrder.LITTLE_ENDIAN}
  • 46 | *
  • {@code ByteOrderParser.parseByteOrder("BIG_ENDIAN")} returns {@code ByteOrder.BIG_ENDIAN}
  • 47 | *
48 | * 49 | * @param value 50 | * the {@code String} containing the ByteOrder representation to be parsed 51 | * @return the ByteOrder represented by the string argument 52 | * @throws IllegalArgumentException 53 | * if the {@code String} containing the ByteOrder representation to be parsed is unknown. 54 | */ 55 | public static ByteOrder parseByteOrder(final String value) { 56 | if (ByteOrder.BIG_ENDIAN.toString().equals(value)) { 57 | return ByteOrder.BIG_ENDIAN; 58 | } 59 | if (ByteOrder.LITTLE_ENDIAN.toString().equals(value)) { 60 | return ByteOrder.LITTLE_ENDIAN; 61 | } 62 | throw new IllegalArgumentException("Unsupported byte order setting: " + value + ", expeced one of " + ByteOrder.LITTLE_ENDIAN + 63 | ", " + ByteOrder.BIG_ENDIAN); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/FileExistsException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io; 18 | 19 | import java.io.File; 20 | import java.io.IOException; 21 | 22 | /** 23 | * Indicates that a file already exists. 24 | * 25 | * @since 2.0 26 | */ 27 | public class FileExistsException extends IOException { 28 | 29 | /** 30 | * Defines the serial version UID. 31 | */ 32 | private static final long serialVersionUID = 1L; 33 | 34 | /** 35 | * Default Constructor. 36 | */ 37 | public FileExistsException() { 38 | super(); 39 | } 40 | 41 | /** 42 | * Construct an instance with the specified message. 43 | * 44 | * @param message The error message 45 | */ 46 | public FileExistsException(final String message) { 47 | super(message); 48 | } 49 | 50 | /** 51 | * Construct an instance with the specified file. 52 | * 53 | * @param file The file that exists 54 | */ 55 | public FileExistsException(final File file) { 56 | super("File " + file + " exists"); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/IOExceptionWithCause.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package org.apache.commons.io; 19 | 20 | import java.io.IOException; 21 | 22 | /** 23 | * Subclasses IOException with the {@link Throwable} constructors missing before Java 6. 24 | * 25 | * @since 1.4 26 | * @deprecated (since 2.5) use {@link IOException} instead 27 | */ 28 | @Deprecated 29 | public class IOExceptionWithCause extends IOException { 30 | 31 | /** 32 | * Defines the serial version UID. 33 | */ 34 | private static final long serialVersionUID = 1L; 35 | 36 | /** 37 | * Constructs a new instance with the given message and cause. 38 | *

39 | * As specified in {@link Throwable}, the message in the given cause is not used in this instance's 40 | * message. 41 | *

42 | * 43 | * @param message 44 | * the message (see {@link #getMessage()}) 45 | * @param cause 46 | * the cause (see {@link #getCause()}). A {@code null} value is allowed. 47 | */ 48 | public IOExceptionWithCause(final String message, final Throwable cause) { 49 | super(message, cause); 50 | } 51 | 52 | /** 53 | * Constructs a new instance with the given cause. 54 | *

55 | * The message is set to cause==null ? null : cause.toString(), which by default contains the class 56 | * and message of cause. This constructor is useful for call sites that just wrap another throwable. 57 | *

58 | * 59 | * @param cause 60 | * the cause (see {@link #getCause()}). A {@code null} value is allowed. 61 | */ 62 | public IOExceptionWithCause(final Throwable cause) { 63 | super(cause); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/TaggedIOException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io; 18 | 19 | import java.io.IOException; 20 | import java.io.Serializable; 21 | 22 | /** 23 | * An {@link IOException} decorator that adds a serializable tag to the 24 | * wrapped exception. Both the tag and the original exception can be used 25 | * to determine further processing when this exception is caught. 26 | * 27 | * @since 2.0 28 | */ 29 | @SuppressWarnings("deprecation") // needs to extend deprecated IOExceptionWithCause to preserve binary compatibility 30 | public class TaggedIOException extends IOExceptionWithCause { 31 | 32 | /** 33 | * Generated serial version UID. 34 | */ 35 | private static final long serialVersionUID = -6994123481142850163L; 36 | 37 | /** 38 | * Checks whether the given throwable is tagged with the given tag. 39 | *

40 | * This check can only succeed if the throwable is a 41 | * {@link TaggedIOException} and the tag is {@link Serializable}, but 42 | * the argument types are intentionally more generic to make it easier 43 | * to use this method without type casts. 44 | *

45 | * A typical use for this method is in a catch block to 46 | * determine how a caught exception should be handled: 47 | *

 48 |      * Serializable tag = ...;
 49 |      * try {
 50 |      *     ...;
 51 |      * } catch (Throwable t) {
 52 |      *     if (TaggedIOExcepton.isTaggedWith(t, tag)) {
 53 |      *         // special processing for tagged exception
 54 |      *     } else {
 55 |      *         // handling of other kinds of exceptions
 56 |      *     }
 57 |      * }
 58 |      * 
59 | * 60 | * @param throwable The Throwable object to check 61 | * @param tag tag object 62 | * @return {@code true} if the throwable has the specified tag, 63 | * otherwise {@code false} 64 | */ 65 | public static boolean isTaggedWith(final Throwable throwable, final Object tag) { 66 | return tag != null 67 | && throwable instanceof TaggedIOException 68 | && tag.equals(((TaggedIOException) throwable).tag); 69 | } 70 | 71 | /** 72 | * Throws the original {@link IOException} if the given throwable is 73 | * a {@link TaggedIOException} decorator the given tag. Does nothing 74 | * if the given throwable is of a different type or if it is tagged 75 | * with some other tag. 76 | *

77 | * This method is typically used in a catch block to 78 | * selectively rethrow tagged exceptions. 79 | *

 80 |      * Serializable tag = ...;
 81 |      * try {
 82 |      *     ...;
 83 |      * } catch (Throwable t) {
 84 |      *     TaggedIOExcepton.throwCauseIfTagged(t, tag);
 85 |      *     // handle other kinds of exceptions
 86 |      * }
 87 |      * 
88 | * 89 | * @param throwable an exception 90 | * @param tag tag object 91 | * @throws IOException original exception from the tagged decorator, if any 92 | */ 93 | public static void throwCauseIfTaggedWith(final Throwable throwable, final Object tag) 94 | throws IOException { 95 | if (isTaggedWith(throwable, tag)) { 96 | throw ((TaggedIOException) throwable).getCause(); 97 | } 98 | } 99 | 100 | /** 101 | * The tag of this exception. 102 | */ 103 | private final Serializable tag; 104 | 105 | /** 106 | * Creates a tagged wrapper for the given exception. 107 | * 108 | * @param original the exception to be tagged 109 | * @param tag tag of this exception 110 | */ 111 | public TaggedIOException(final IOException original, final Serializable tag) { 112 | super(original.getMessage(), original); 113 | this.tag = tag; 114 | } 115 | 116 | /** 117 | * Returns the serializable tag object. 118 | * 119 | * @return tag object 120 | */ 121 | public Serializable getTag() { 122 | return tag; 123 | } 124 | 125 | /** 126 | * Returns the wrapped exception. The only difference to the overridden 127 | * {@link Throwable#getCause()} method is the narrower return type. 128 | * 129 | * @return wrapped exception 130 | */ 131 | @Override 132 | public IOException getCause() { 133 | return (IOException) super.getCause(); 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/ThreadMonitor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io; 18 | 19 | /** 20 | * Monitors a thread, interrupting it if it reaches the specified timeout. 21 | *

22 | * This works by sleeping until the specified timeout amount and then 23 | * interrupting the thread being monitored. If the thread being monitored 24 | * completes its work before being interrupted, it should interrupt() 25 | * the monitor thread. 26 | *

27 | * 28 | *
 29 |  *       long timeoutInMillis = 1000;
 30 |  *       try {
 31 |  *           Thread monitor = ThreadMonitor.start(timeoutInMillis);
 32 |  *           // do some work here
 33 |  *           ThreadMonitor.stop(monitor);
 34 |  *       } catch (InterruptedException e) {
 35 |  *           // timed amount was reached
 36 |  *       }
 37 |  * 
38 | * 39 | */ 40 | class ThreadMonitor implements Runnable { 41 | 42 | private final Thread thread; 43 | private final long timeout; 44 | 45 | /** 46 | * Start monitoring the current thread. 47 | * 48 | * @param timeout The timeout amount in milliseconds 49 | * or no timeout if the value is zero or less 50 | * @return The monitor thread or {@code null} 51 | * if the timeout amount is not greater than zero 52 | */ 53 | public static Thread start(final long timeout) { 54 | return start(Thread.currentThread(), timeout); 55 | } 56 | 57 | /** 58 | * Start monitoring the specified thread. 59 | * 60 | * @param thread The thread The thread to monitor 61 | * @param timeout The timeout amount in milliseconds 62 | * or no timeout if the value is zero or less 63 | * @return The monitor thread or {@code null} 64 | * if the timeout amount is not greater than zero 65 | */ 66 | public static Thread start(final Thread thread, final long timeout) { 67 | Thread monitor = null; 68 | if (timeout > 0) { 69 | final ThreadMonitor timout = new ThreadMonitor(thread, timeout); 70 | monitor = new Thread(timout, ThreadMonitor.class.getSimpleName()); 71 | monitor.setDaemon(true); 72 | monitor.start(); 73 | } 74 | return monitor; 75 | } 76 | 77 | /** 78 | * Stop monitoring the specified thread. 79 | * 80 | * @param thread The monitor thread, may be {@code null} 81 | */ 82 | public static void stop(final Thread thread) { 83 | if (thread != null) { 84 | thread.interrupt(); 85 | } 86 | } 87 | 88 | /** 89 | * Construct and new monitor. 90 | * 91 | * @param thread The thread to monitor 92 | * @param timeout The timeout amount in milliseconds 93 | */ 94 | private ThreadMonitor(final Thread thread, final long timeout) { 95 | this.thread = thread; 96 | this.timeout = timeout; 97 | } 98 | 99 | /** 100 | * Sleep until the specified timeout amount and then 101 | * interrupt the thread being monitored. 102 | * 103 | * @see Runnable#run() 104 | */ 105 | @Override 106 | public void run() { 107 | try { 108 | sleep(timeout); 109 | thread.interrupt(); 110 | } catch (final InterruptedException e) { 111 | // timeout not reached 112 | } 113 | } 114 | 115 | /** 116 | * Sleep for a guaranteed minimum number of milliseconds unless interrupted. 117 | * 118 | * This method exists because Thread.sleep(100) can sleep for 0, 70, 100 or 200ms or anything else 119 | * it deems appropriate. Read the docs on Thread.sleep for further interesting details. 120 | * 121 | * @param ms the number of milliseconds to sleep for 122 | * @throws InterruptedException if interrupted 123 | */ 124 | private static void sleep(final long ms) throws InterruptedException { 125 | final long finishAt = System.currentTimeMillis() + ms; 126 | long remaining = ms; 127 | do { 128 | Thread.sleep(remaining); 129 | remaining = finishAt - System.currentTimeMillis(); 130 | } while (remaining > 0); 131 | } 132 | 133 | 134 | } -------------------------------------------------------------------------------- /src/org/apache/commons/io/comparator/AbstractFileComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.comparator; 18 | 19 | import java.io.File; 20 | import java.util.Arrays; 21 | import java.util.Collections; 22 | import java.util.Comparator; 23 | import java.util.List; 24 | 25 | /** 26 | * Abstract file {@link Comparator} which provides sorting for file arrays and lists. 27 | * 28 | * @since 2.0 29 | */ 30 | abstract class AbstractFileComparator implements Comparator { 31 | 32 | /** 33 | * Sort an array of files. 34 | *

35 | * This method uses {@link Arrays#sort(Object[], Comparator)} 36 | * and returns the original array. 37 | * 38 | * @param files The files to sort, may be null 39 | * @return The sorted array 40 | * @since 2.0 41 | */ 42 | public File[] sort(final File... files) { 43 | if (files != null) { 44 | Arrays.sort(files, this); 45 | } 46 | return files; 47 | } 48 | 49 | /** 50 | * Sort a List of files. 51 | *

52 | * This method uses {@link Collections#sort(List, Comparator)} 53 | * and returns the original list. 54 | * 55 | * @param files The files to sort, may be null 56 | * @return The sorted list 57 | * @since 2.0 58 | */ 59 | public List sort(final List files) { 60 | if (files != null) { 61 | Collections.sort(files, this); 62 | } 63 | return files; 64 | } 65 | 66 | /** 67 | * String representation of this file comparator. 68 | * 69 | * @return String representation of this file comparator 70 | */ 71 | @Override 72 | public String toString() { 73 | return getClass().getSimpleName(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/comparator/CompositeFileComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.comparator; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | import java.util.ArrayList; 22 | import java.util.Comparator; 23 | import java.util.List; 24 | 25 | /** 26 | * Compare two files using a set of delegate file {@link Comparator}. 27 | *

28 | * This comparator can be used to sort lists or arrays of files 29 | * by combining a number other comparators. 30 | *

31 | * Example of sorting a list of files by type (i.e. directory or file) 32 | * and then by name: 33 | *

 34 |  *       CompositeFileComparator comparator =
 35 |  *                       new CompositeFileComparator(
 36 |  *                                 (AbstractFileComparator) DirectoryFileComparator.DIRECTORY_COMPARATOR,
 37 |  *                                 (AbstractFileComparator) NameFileComparator.NAME_COMPARATOR);
 38 |  *       List<File> list = ...
 39 |  *       comparator.sort(list);
 40 |  * 
41 | * 42 | * @since 2.0 43 | */ 44 | public class CompositeFileComparator extends AbstractFileComparator implements Serializable { 45 | 46 | private static final long serialVersionUID = -2224170307287243428L; 47 | private static final Comparator[] NO_COMPARATORS = {}; 48 | private final Comparator[] delegates; 49 | 50 | /** 51 | * Create a composite comparator for the set of delegate comparators. 52 | * 53 | * @param delegates The delegate file comparators 54 | */ 55 | @SuppressWarnings("unchecked") // casts 1 & 2 must be OK because types are already correct 56 | public CompositeFileComparator(final Comparator... delegates) { 57 | if (delegates == null) { 58 | this.delegates = (Comparator[]) NO_COMPARATORS;//1 59 | } else { 60 | this.delegates = (Comparator[]) new Comparator[delegates.length];//2 61 | System.arraycopy(delegates, 0, this.delegates, 0, delegates.length); 62 | } 63 | } 64 | 65 | /** 66 | * Create a composite comparator for the set of delegate comparators. 67 | * 68 | * @param delegates The delegate file comparators 69 | */ 70 | @SuppressWarnings("unchecked") // casts 1 & 2 must be OK because types are already correct 71 | public CompositeFileComparator(final Iterable> delegates) { 72 | if (delegates == null) { 73 | this.delegates = (Comparator[]) NO_COMPARATORS; //1 74 | } else { 75 | final List> list = new ArrayList<>(); 76 | for (final Comparator comparator : delegates) { 77 | list.add(comparator); 78 | } 79 | this.delegates = (Comparator[]) list.toArray(new Comparator[list.size()]); //2 80 | } 81 | } 82 | 83 | /** 84 | * Compare the two files using delegate comparators. 85 | * 86 | * @param file1 The first file to compare 87 | * @param file2 The second file to compare 88 | * @return the first non-zero result returned from 89 | * the delegate comparators or zero. 90 | */ 91 | @Override 92 | public int compare(final File file1, final File file2) { 93 | int result = 0; 94 | for (final Comparator delegate : delegates) { 95 | result = delegate.compare(file1, file2); 96 | if (result != 0) { 97 | break; 98 | } 99 | } 100 | return result; 101 | } 102 | 103 | /** 104 | * String representation of this file comparator. 105 | * 106 | * @return String representation of this file comparator 107 | */ 108 | @Override 109 | public String toString() { 110 | final StringBuilder builder = new StringBuilder(); 111 | builder.append(super.toString()); 112 | builder.append('{'); 113 | for (int i = 0; i < delegates.length; i++) { 114 | if (i > 0) { 115 | builder.append(','); 116 | } 117 | builder.append(delegates[i]); 118 | } 119 | builder.append('}'); 120 | return builder.toString(); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/comparator/DefaultFileComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.comparator; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | import java.util.Comparator; 22 | 23 | /** 24 | * Compare two files using the default {@link File#compareTo(File)} method. 25 | *

26 | * This comparator can be used to sort lists or arrays of files 27 | * by using the default file comparison. 28 | *

29 | * Example of sorting a list of files using the 30 | * {@link #DEFAULT_COMPARATOR} singleton instance: 31 | *

32 |  *       List<File> list = ...
33 |  *       ((AbstractFileComparator) DefaultFileComparator.DEFAULT_COMPARATOR).sort(list);
34 |  * 
35 | *

36 | * Example of doing a reverse sort of an array of files using the 37 | * {@link #DEFAULT_REVERSE} singleton instance: 38 | *

39 |  *       File[] array = ...
40 |  *       ((AbstractFileComparator) DefaultFileComparator.DEFAULT_REVERSE).sort(array);
41 |  * 
42 | *

43 | * 44 | * @since 1.4 45 | */ 46 | public class DefaultFileComparator extends AbstractFileComparator implements Serializable { 47 | 48 | private static final long serialVersionUID = 3260141861365313518L; 49 | 50 | /** Singleton default comparator instance */ 51 | public static final Comparator DEFAULT_COMPARATOR = new DefaultFileComparator(); 52 | 53 | /** Singleton reverse default comparator instance */ 54 | public static final Comparator DEFAULT_REVERSE = new ReverseComparator(DEFAULT_COMPARATOR); 55 | 56 | /** 57 | * Compare the two files using the {@link File#compareTo(File)} method. 58 | * 59 | * @param file1 The first file to compare 60 | * @param file2 The second file to compare 61 | * @return the result of calling file1's 62 | * {@link File#compareTo(File)} with file2 as the parameter. 63 | */ 64 | @Override 65 | public int compare(final File file1, final File file2) { 66 | return file1.compareTo(file2); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/comparator/DirectoryFileComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.comparator; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | import java.util.Comparator; 22 | 23 | /** 24 | * Compare two files using the {@link File#isDirectory()} method. 25 | *

26 | * This comparator can be used to sort lists or arrays by directories and files. 27 | *

28 | * Example of sorting a list of files/directories using the 29 | * {@link #DIRECTORY_COMPARATOR} singleton instance: 30 | *

31 |  *       List<File> list = ...
32 |  *       ((AbstractFileComparator) DirectoryFileComparator.DIRECTORY_COMPARATOR).sort(list);
33 |  * 
34 | *

35 | * Example of doing a reverse sort of an array of files/directories using the 36 | * {@link #DIRECTORY_REVERSE} singleton instance: 37 | *

38 |  *       File[] array = ...
39 |  *       ((AbstractFileComparator) DirectoryFileComparator.DIRECTORY_REVERSE).sort(array);
40 |  * 
41 | *

42 | * 43 | * @since 2.0 44 | */ 45 | public class DirectoryFileComparator extends AbstractFileComparator implements Serializable { 46 | 47 | private static final long serialVersionUID = 296132640160964395L; 48 | 49 | /** Singleton default comparator instance */ 50 | public static final Comparator DIRECTORY_COMPARATOR = new DirectoryFileComparator(); 51 | 52 | /** Singleton reverse default comparator instance */ 53 | public static final Comparator DIRECTORY_REVERSE = new ReverseComparator(DIRECTORY_COMPARATOR); 54 | 55 | /** 56 | * Compare the two files using the {@link File#isDirectory()} method. 57 | * 58 | * @param file1 The first file to compare 59 | * @param file2 The second file to compare 60 | * @return the result of calling file1's 61 | * {@link File#compareTo(File)} with file2 as the parameter. 62 | */ 63 | @Override 64 | public int compare(final File file1, final File file2) { 65 | return getType(file1) - getType(file2); 66 | } 67 | 68 | /** 69 | * Convert type to numeric value. 70 | * 71 | * @param file The file 72 | * @return 1 for directories and 2 for files 73 | */ 74 | private int getType(final File file) { 75 | if (file.isDirectory()) { 76 | return 1; 77 | } else { 78 | return 2; 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/comparator/LastModifiedFileComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.comparator; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | import java.util.Comparator; 22 | 23 | /** 24 | * Compare the last modified date/time of two files for order 25 | * (see {@link File#lastModified()}). 26 | *

27 | * This comparator can be used to sort lists or arrays of files 28 | * by their last modified date/time. 29 | *

30 | * Example of sorting a list of files using the 31 | * {@link #LASTMODIFIED_COMPARATOR} singleton instance: 32 | *

33 |  *       List<File> list = ...
34 |  *       ((AbstractFileComparator) LastModifiedFileComparator.LASTMODIFIED_COMPARATOR).sort(list);
35 |  * 
36 | *

37 | * Example of doing a reverse sort of an array of files using the 38 | * {@link #LASTMODIFIED_REVERSE} singleton instance: 39 | *

40 |  *       File[] array = ...
41 |  *       ((AbstractFileComparator) LastModifiedFileComparator.LASTMODIFIED_REVERSE).sort(array);
42 |  * 
43 | *

44 | * 45 | * @since 1.4 46 | */ 47 | public class LastModifiedFileComparator extends AbstractFileComparator implements Serializable { 48 | 49 | private static final long serialVersionUID = 7372168004395734046L; 50 | 51 | /** Last modified comparator instance */ 52 | public static final Comparator LASTMODIFIED_COMPARATOR = new LastModifiedFileComparator(); 53 | 54 | /** Reverse last modified comparator instance */ 55 | public static final Comparator LASTMODIFIED_REVERSE = new ReverseComparator(LASTMODIFIED_COMPARATOR); 56 | 57 | /** 58 | * Compare the last the last modified date/time of two files. 59 | * 60 | * @param file1 The first file to compare 61 | * @param file2 The second file to compare 62 | * @return a negative value if the first file's lastmodified date/time 63 | * is less than the second, zero if the lastmodified date/time are the 64 | * same and a positive value if the first files lastmodified date/time 65 | * is greater than the second file. 66 | * 67 | */ 68 | @Override 69 | public int compare(final File file1, final File file2) { 70 | final long result = file1.lastModified() - file2.lastModified(); 71 | if (result < 0) { 72 | return -1; 73 | } else if (result > 0) { 74 | return 1; 75 | } else { 76 | return 0; 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/comparator/NameFileComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.comparator; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | import java.util.Comparator; 22 | 23 | import org.apache.commons.io.IOCase; 24 | 25 | /** 26 | * Compare the names of two files for order (see {@link File#getName()}). 27 | *

28 | * This comparator can be used to sort lists or arrays of files 29 | * by their name either in a case-sensitive, case-insensitive or 30 | * system dependent case sensitive way. A number of singleton instances 31 | * are provided for the various case sensitivity options (using {@link IOCase}) 32 | * and the reverse of those options. 33 | *

34 | * Example of a case-sensitive file name sort using the 35 | * {@link #NAME_COMPARATOR} singleton instance: 36 | *

 37 |  *       List<File> list = ...
 38 |  *       ((AbstractFileComparator) NameFileComparator.NAME_COMPARATOR).sort(list);
 39 |  * 
40 | *

41 | * Example of a reverse case-insensitive file name sort using the 42 | * {@link #NAME_INSENSITIVE_REVERSE} singleton instance: 43 | *

 44 |  *       File[] array = ...
 45 |  *       ((AbstractFileComparator) NameFileComparator.NAME_INSENSITIVE_REVERSE).sort(array);
 46 |  * 
47 | *

48 | * 49 | * @since 1.4 50 | */ 51 | public class NameFileComparator extends AbstractFileComparator implements Serializable { 52 | 53 | private static final long serialVersionUID = 8397947749814525798L; 54 | 55 | /** Case-sensitive name comparator instance (see {@link IOCase#SENSITIVE}) */ 56 | public static final Comparator NAME_COMPARATOR = new NameFileComparator(); 57 | 58 | /** Reverse case-sensitive name comparator instance (see {@link IOCase#SENSITIVE}) */ 59 | public static final Comparator NAME_REVERSE = new ReverseComparator(NAME_COMPARATOR); 60 | 61 | /** Case-insensitive name comparator instance (see {@link IOCase#INSENSITIVE}) */ 62 | public static final Comparator NAME_INSENSITIVE_COMPARATOR = new NameFileComparator(IOCase.INSENSITIVE); 63 | 64 | /** Reverse case-insensitive name comparator instance (see {@link IOCase#INSENSITIVE}) */ 65 | public static final Comparator NAME_INSENSITIVE_REVERSE = new ReverseComparator(NAME_INSENSITIVE_COMPARATOR); 66 | 67 | /** System sensitive name comparator instance (see {@link IOCase#SYSTEM}) */ 68 | public static final Comparator NAME_SYSTEM_COMPARATOR = new NameFileComparator(IOCase.SYSTEM); 69 | 70 | /** Reverse system sensitive name comparator instance (see {@link IOCase#SYSTEM}) */ 71 | public static final Comparator NAME_SYSTEM_REVERSE = new ReverseComparator(NAME_SYSTEM_COMPARATOR); 72 | 73 | /** Whether the comparison is case sensitive. */ 74 | private final IOCase caseSensitivity; 75 | 76 | /** 77 | * Construct a case sensitive file name comparator instance. 78 | */ 79 | public NameFileComparator() { 80 | this.caseSensitivity = IOCase.SENSITIVE; 81 | } 82 | 83 | /** 84 | * Construct a file name comparator instance with the specified case-sensitivity. 85 | * 86 | * @param caseSensitivity how to handle case sensitivity, null means case-sensitive 87 | */ 88 | public NameFileComparator(final IOCase caseSensitivity) { 89 | this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; 90 | } 91 | 92 | /** 93 | * Compare the names of two files with the specified case sensitivity. 94 | * 95 | * @param file1 The first file to compare 96 | * @param file2 The second file to compare 97 | * @return a negative value if the first file's name 98 | * is less than the second, zero if the names are the 99 | * same and a positive value if the first files name 100 | * is greater than the second file. 101 | */ 102 | @Override 103 | public int compare(final File file1, final File file2) { 104 | return caseSensitivity.checkCompareTo(file1.getName(), file2.getName()); 105 | } 106 | 107 | /** 108 | * String representation of this file comparator. 109 | * 110 | * @return String representation of this file comparator 111 | */ 112 | @Override 113 | public String toString() { 114 | return super.toString() + "[caseSensitivity=" + caseSensitivity + "]"; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/comparator/PathFileComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.comparator; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | import java.util.Comparator; 22 | 23 | import org.apache.commons.io.IOCase; 24 | 25 | /** 26 | * Compare the path of two files for order (see {@link File#getPath()}). 27 | *

28 | * This comparator can be used to sort lists or arrays of files 29 | * by their path either in a case-sensitive, case-insensitive or 30 | * system dependent case sensitive way. A number of singleton instances 31 | * are provided for the various case sensitivity options (using {@link IOCase}) 32 | * and the reverse of those options. 33 | *

34 | * Example of a case-sensitive file path sort using the 35 | * {@link #PATH_COMPARATOR} singleton instance: 36 | *

 37 |  *       List<File> list = ...
 38 |  *       ((AbstractFileComparator) PathFileComparator.PATH_COMPARATOR).sort(list);
 39 |  * 
40 | *

41 | * Example of a reverse case-insensitive file path sort using the 42 | * {@link #PATH_INSENSITIVE_REVERSE} singleton instance: 43 | *

 44 |  *       File[] array = ...
 45 |  *       ((AbstractFileComparator) PathFileComparator.PATH_INSENSITIVE_REVERSE).sort(array);
 46 |  * 
47 | *

48 | * 49 | * @since 1.4 50 | */ 51 | public class PathFileComparator extends AbstractFileComparator implements Serializable { 52 | 53 | private static final long serialVersionUID = 6527501707585768673L; 54 | 55 | /** Case-sensitive path comparator instance (see {@link IOCase#SENSITIVE}) */ 56 | public static final Comparator PATH_COMPARATOR = new PathFileComparator(); 57 | 58 | /** Reverse case-sensitive path comparator instance (see {@link IOCase#SENSITIVE}) */ 59 | public static final Comparator PATH_REVERSE = new ReverseComparator(PATH_COMPARATOR); 60 | 61 | /** Case-insensitive path comparator instance (see {@link IOCase#INSENSITIVE}) */ 62 | public static final Comparator PATH_INSENSITIVE_COMPARATOR = new PathFileComparator(IOCase.INSENSITIVE); 63 | 64 | /** Reverse case-insensitive path comparator instance (see {@link IOCase#INSENSITIVE}) */ 65 | public static final Comparator PATH_INSENSITIVE_REVERSE = new ReverseComparator(PATH_INSENSITIVE_COMPARATOR); 66 | 67 | /** System sensitive path comparator instance (see {@link IOCase#SYSTEM}) */ 68 | public static final Comparator PATH_SYSTEM_COMPARATOR = new PathFileComparator(IOCase.SYSTEM); 69 | 70 | /** Reverse system sensitive path comparator instance (see {@link IOCase#SYSTEM}) */ 71 | public static final Comparator PATH_SYSTEM_REVERSE = new ReverseComparator(PATH_SYSTEM_COMPARATOR); 72 | 73 | /** Whether the comparison is case sensitive. */ 74 | private final IOCase caseSensitivity; 75 | 76 | /** 77 | * Construct a case sensitive file path comparator instance. 78 | */ 79 | public PathFileComparator() { 80 | this.caseSensitivity = IOCase.SENSITIVE; 81 | } 82 | 83 | /** 84 | * Construct a file path comparator instance with the specified case-sensitivity. 85 | * 86 | * @param caseSensitivity how to handle case sensitivity, null means case-sensitive 87 | */ 88 | public PathFileComparator(final IOCase caseSensitivity) { 89 | this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity; 90 | } 91 | 92 | /** 93 | * Compare the paths of two files the specified case sensitivity. 94 | * 95 | * @param file1 The first file to compare 96 | * @param file2 The second file to compare 97 | * @return a negative value if the first file's path 98 | * is less than the second, zero if the paths are the 99 | * same and a positive value if the first files path 100 | * is greater than the second file. 101 | * 102 | */ 103 | @Override 104 | public int compare(final File file1, final File file2) { 105 | return caseSensitivity.checkCompareTo(file1.getPath(), file2.getPath()); 106 | } 107 | 108 | /** 109 | * String representation of this file comparator. 110 | * 111 | * @return String representation of this file comparator 112 | */ 113 | @Override 114 | public String toString() { 115 | return super.toString() + "[caseSensitivity=" + caseSensitivity + "]"; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/comparator/ReverseComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.comparator; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | import java.util.Comparator; 22 | 23 | /** 24 | * Reverses the result of comparing two objects using 25 | * the delegate {@link Comparator}. 26 | * 27 | * @since 1.4 28 | */ 29 | class ReverseComparator extends AbstractFileComparator implements Serializable { 30 | 31 | private static final long serialVersionUID = -4808255005272229056L; 32 | private final Comparator delegate; 33 | 34 | /** 35 | * Construct an instance with the specified delegate {@link Comparator}. 36 | * 37 | * @param delegate The comparator to delegate to 38 | */ 39 | public ReverseComparator(final Comparator delegate) { 40 | if (delegate == null) { 41 | throw new IllegalArgumentException("Delegate comparator is missing"); 42 | } 43 | this.delegate = delegate; 44 | } 45 | 46 | /** 47 | * Compare using the delegate Comparator, but reversing the result. 48 | * 49 | * @param file1 The first file to compare 50 | * @param file2 The second file to compare 51 | * @return the result from the delegate {@link Comparator#compare(Object, Object)} 52 | * reversing the value (i.e. positive becomes negative and vice versa) 53 | */ 54 | @Override 55 | public int compare(final File file1, final File file2) { 56 | return delegate.compare(file2, file1); // parameters switched round 57 | } 58 | 59 | /** 60 | * String representation of this file comparator. 61 | * 62 | * @return String representation of this file comparator 63 | */ 64 | @Override 65 | public String toString() { 66 | return super.toString() + "[" + delegate.toString() + "]"; 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/AbstractFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | 21 | /** 22 | * An abstract class which implements the Java FileFilter and FilenameFilter 23 | * interfaces via the IOFileFilter interface. 24 | *

25 | * Note that a subclass must override one of the accept methods, 26 | * otherwise your class will infinitely loop. 27 | * 28 | * @since 1.0 29 | * @version $Id$ 30 | */ 31 | public abstract class AbstractFileFilter implements IOFileFilter { 32 | 33 | /** 34 | * Checks to see if the File should be accepted by this filter. 35 | * 36 | * @param file the File to check 37 | * @return true if this file matches the test 38 | */ 39 | @Override 40 | public boolean accept(final File file) { 41 | return accept(file.getParentFile(), file.getName()); 42 | } 43 | 44 | /** 45 | * Checks to see if the File should be accepted by this filter. 46 | * 47 | * @param dir the directory File to check 48 | * @param name the filename within the directory to check 49 | * @return true if this file matches the test 50 | */ 51 | @Override 52 | public boolean accept(final File dir, final String name) { 53 | return accept(new File(dir, name)); 54 | } 55 | 56 | /** 57 | * Provide a String representation of this file filter. 58 | * 59 | * @return a String representation 60 | */ 61 | @Override 62 | public String toString() { 63 | return getClass().getSimpleName(); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/CanReadFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | 22 | /** 23 | * This filter accepts Files that can be read. 24 | *

25 | * Example, showing how to print out a list of the 26 | * current directory's readable files: 27 | * 28 | *

29 |  * File dir = new File(".");
30 |  * String[] files = dir.list( CanReadFileFilter.CAN_READ );
31 |  * for ( int i = 0; i < files.length; i++ ) {
32 |  *     System.out.println(files[i]);
33 |  * }
34 |  * 
35 | * 36 | *

37 | * Example, showing how to print out a list of the 38 | * current directory's un-readable files: 39 | * 40 | *

41 |  * File dir = new File(".");
42 |  * String[] files = dir.list( CanReadFileFilter.CANNOT_READ );
43 |  * for ( int i = 0; i < files.length; i++ ) {
44 |  *     System.out.println(files[i]);
45 |  * }
46 |  * 
47 | * 48 | *

49 | * Example, showing how to print out a list of the 50 | * current directory's read-only files: 51 | * 52 | *

53 |  * File dir = new File(".");
54 |  * String[] files = dir.list( CanReadFileFilter.READ_ONLY );
55 |  * for ( int i = 0; i < files.length; i++ ) {
56 |  *     System.out.println(files[i]);
57 |  * }
58 |  * 
59 | * 60 | * @since 1.3 61 | * @version $Id$ 62 | */ 63 | public class CanReadFileFilter extends AbstractFileFilter implements Serializable { 64 | 65 | private static final long serialVersionUID = 3179904805251622989L; 66 | 67 | /** Singleton instance of readable filter */ 68 | public static final IOFileFilter CAN_READ = new CanReadFileFilter(); 69 | 70 | /** Singleton instance of not readable filter */ 71 | public static final IOFileFilter CANNOT_READ = new NotFileFilter(CAN_READ); 72 | 73 | /** Singleton instance of read-only filter */ 74 | public static final IOFileFilter READ_ONLY = new AndFileFilter(CAN_READ, 75 | CanWriteFileFilter.CANNOT_WRITE); 76 | 77 | /** 78 | * Restrictive constructor. 79 | */ 80 | protected CanReadFileFilter() { 81 | } 82 | 83 | /** 84 | * Checks to see if the file can be read. 85 | * 86 | * @param file the File to check. 87 | * @return {@code true} if the file can be 88 | * read, otherwise {@code false}. 89 | */ 90 | @Override 91 | public boolean accept(final File file) { 92 | return file.canRead(); 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/CanWriteFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | 22 | /** 23 | * This filter accepts Files that can be written to. 24 | *

25 | * Example, showing how to print out a list of the 26 | * current directory's writable files: 27 | * 28 | *

29 |  * File dir = new File(".");
30 |  * String[] files = dir.list( CanWriteFileFilter.CAN_WRITE );
31 |  * for ( int i = 0; i < files.length; i++ ) {
32 |  *     System.out.println(files[i]);
33 |  * }
34 |  * 
35 | * 36 | *

37 | * Example, showing how to print out a list of the 38 | * current directory's un-writable files: 39 | * 40 | *

41 |  * File dir = new File(".");
42 |  * String[] files = dir.list( CanWriteFileFilter.CANNOT_WRITE );
43 |  * for ( int i = 0; i < files.length; i++ ) {
44 |  *     System.out.println(files[i]);
45 |  * }
46 |  * 
47 | * 48 | *

49 | * N.B. For read-only files, use 50 | * CanReadFileFilter.READ_ONLY. 51 | * 52 | * @since 1.3 53 | * @version $Id$ 54 | */ 55 | public class CanWriteFileFilter extends AbstractFileFilter implements Serializable { 56 | 57 | private static final long serialVersionUID = 5132005214688990379L; 58 | 59 | /** Singleton instance of writable filter */ 60 | public static final IOFileFilter CAN_WRITE = new CanWriteFileFilter(); 61 | 62 | /** Singleton instance of not writable filter */ 63 | public static final IOFileFilter CANNOT_WRITE = new NotFileFilter(CAN_WRITE); 64 | 65 | /** 66 | * Restrictive constructor. 67 | */ 68 | protected CanWriteFileFilter() { 69 | } 70 | 71 | /** 72 | * Checks to see if the file can be written to. 73 | * 74 | * @param file the File to check 75 | * @return {@code true} if the file can be 76 | * written to, otherwise {@code false}. 77 | */ 78 | @Override 79 | public boolean accept(final File file) { 80 | return file.canWrite(); 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/ConditionalFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.util.List; 20 | 21 | /** 22 | * Defines operations for conditional file filters. 23 | * 24 | * @since 1.1 25 | * @version $Id$ 26 | */ 27 | public interface ConditionalFileFilter { 28 | 29 | /** 30 | * Adds the specified file filter to the list of file filters at the end of 31 | * the list. 32 | * 33 | * @param ioFileFilter the filter to be added 34 | * @since 1.1 35 | */ 36 | void addFileFilter(IOFileFilter ioFileFilter); 37 | 38 | /** 39 | * Returns this conditional file filter's list of file filters. 40 | * 41 | * @return the file filter list 42 | * @since 1.1 43 | */ 44 | List getFileFilters(); 45 | 46 | /** 47 | * Removes the specified file filter. 48 | * 49 | * @param ioFileFilter filter to be removed 50 | * @return {@code true} if the filter was found in the list, 51 | * {@code false} otherwise 52 | * @since 1.1 53 | */ 54 | boolean removeFileFilter(IOFileFilter ioFileFilter); 55 | 56 | /** 57 | * Sets the list of file filters, replacing any previously configured 58 | * file filters on this filter. 59 | * 60 | * @param fileFilters the list of filters 61 | * @since 1.1 62 | */ 63 | void setFileFilters(List fileFilters); 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/DelegateFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.FileFilter; 21 | import java.io.FilenameFilter; 22 | import java.io.Serializable; 23 | 24 | /** 25 | * This class turns a Java FileFilter or FilenameFilter into an IO FileFilter. 26 | * 27 | * @since 1.0 28 | * @version $Id$ 29 | * 30 | * @see FileFilterUtils#asFileFilter(FileFilter) 31 | * @see FileFilterUtils#asFileFilter(FilenameFilter) 32 | */ 33 | public class DelegateFileFilter extends AbstractFileFilter implements Serializable { 34 | 35 | private static final long serialVersionUID = -8723373124984771318L; 36 | /** The Filename filter */ 37 | private final FilenameFilter filenameFilter; 38 | /** The File filter */ 39 | private final FileFilter fileFilter; 40 | 41 | /** 42 | * Constructs a delegate file filter around an existing FilenameFilter. 43 | * 44 | * @param filter the filter to decorate 45 | */ 46 | public DelegateFileFilter(final FilenameFilter filter) { 47 | if (filter == null) { 48 | throw new IllegalArgumentException("The FilenameFilter must not be null"); 49 | } 50 | this.filenameFilter = filter; 51 | this.fileFilter = null; 52 | } 53 | 54 | /** 55 | * Constructs a delegate file filter around an existing FileFilter. 56 | * 57 | * @param filter the filter to decorate 58 | */ 59 | public DelegateFileFilter(final FileFilter filter) { 60 | if (filter == null) { 61 | throw new IllegalArgumentException("The FileFilter must not be null"); 62 | } 63 | this.fileFilter = filter; 64 | this.filenameFilter = null; 65 | } 66 | 67 | /** 68 | * Checks the filter. 69 | * 70 | * @param file the file to check 71 | * @return true if the filter matches 72 | */ 73 | @Override 74 | public boolean accept(final File file) { 75 | if (fileFilter != null) { 76 | return fileFilter.accept(file); 77 | } else { 78 | return super.accept(file); 79 | } 80 | } 81 | 82 | /** 83 | * Checks the filter. 84 | * 85 | * @param dir the directory 86 | * @param name the filename in the directory 87 | * @return true if the filter matches 88 | */ 89 | @Override 90 | public boolean accept(final File dir, final String name) { 91 | if (filenameFilter != null) { 92 | return filenameFilter.accept(dir, name); 93 | } else { 94 | return super.accept(dir, name); 95 | } 96 | } 97 | 98 | /** 99 | * Provide a String representation of this file filter. 100 | * 101 | * @return a String representation 102 | */ 103 | @Override 104 | public String toString() { 105 | final String delegate = fileFilter != null ? fileFilter.toString() : filenameFilter.toString(); 106 | return super.toString() + "(" + delegate + ")"; 107 | } 108 | 109 | } 110 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/DirectoryFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | 22 | /** 23 | * This filter accepts Files that are directories. 24 | *

25 | * For example, here is how to print out a list of the 26 | * current directory's subdirectories: 27 | * 28 | *

29 |  * File dir = new File(".");
30 |  * String[] files = dir.list( DirectoryFileFilter.INSTANCE );
31 |  * for ( int i = 0; i < files.length; i++ ) {
32 |  *     System.out.println(files[i]);
33 |  * }
34 |  * 
35 | * 36 | * @since 1.0 37 | * @version $Id$ 38 | * 39 | * @see FileFilterUtils#directoryFileFilter() 40 | */ 41 | public class DirectoryFileFilter extends AbstractFileFilter implements Serializable { 42 | 43 | private static final long serialVersionUID = -5148237843784525732L; 44 | /** 45 | * Singleton instance of directory filter. 46 | * @since 1.3 47 | */ 48 | public static final IOFileFilter DIRECTORY = new DirectoryFileFilter(); 49 | /** 50 | * Singleton instance of directory filter. 51 | * Please use the identical DirectoryFileFilter.DIRECTORY constant. 52 | * The new name is more JDK 1.5 friendly as it doesn't clash with other 53 | * values when using static imports. 54 | */ 55 | public static final IOFileFilter INSTANCE = DIRECTORY; 56 | 57 | /** 58 | * Restrictive constructor. 59 | */ 60 | protected DirectoryFileFilter() { 61 | } 62 | 63 | /** 64 | * Checks to see if the file is a directory. 65 | * 66 | * @param file the File to check 67 | * @return true if the file is a directory 68 | */ 69 | @Override 70 | public boolean accept(final File file) { 71 | return file.isDirectory(); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/EmptyFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | 22 | /** 23 | * This filter accepts files or directories that are empty. 24 | *

25 | * If the File is a directory it checks that 26 | * it contains no files. 27 | *

28 | * Example, showing how to print out a list of the 29 | * current directory's empty files/directories: 30 | * 31 | *

32 |  * File dir = new File(".");
33 |  * String[] files = dir.list( EmptyFileFilter.EMPTY );
34 |  * for ( int i = 0; i < files.length; i++ ) {
35 |  *     System.out.println(files[i]);
36 |  * }
37 |  * 
38 | * 39 | *

40 | * Example, showing how to print out a list of the 41 | * current directory's non-empty files/directories: 42 | * 43 | *

44 |  * File dir = new File(".");
45 |  * String[] files = dir.list( EmptyFileFilter.NOT_EMPTY );
46 |  * for ( int i = 0; i < files.length; i++ ) {
47 |  *     System.out.println(files[i]);
48 |  * }
49 |  * 
50 | * 51 | * @since 1.3 52 | * @version $Id$ 53 | */ 54 | public class EmptyFileFilter extends AbstractFileFilter implements Serializable { 55 | 56 | private static final long serialVersionUID = 3631422087512832211L; 57 | 58 | /** Singleton instance of empty filter */ 59 | public static final IOFileFilter EMPTY = new EmptyFileFilter(); 60 | 61 | /** Singleton instance of not-empty filter */ 62 | public static final IOFileFilter NOT_EMPTY = new NotFileFilter(EMPTY); 63 | 64 | /** 65 | * Restrictive constructor. 66 | */ 67 | protected EmptyFileFilter() { 68 | } 69 | 70 | /** 71 | * Checks to see if the file is empty. 72 | * 73 | * @param file the file or directory to check 74 | * @return {@code true} if the file or directory 75 | * is empty, otherwise {@code false}. 76 | */ 77 | @Override 78 | public boolean accept(final File file) { 79 | if (file.isDirectory()) { 80 | final File[] files = file.listFiles(); 81 | return files == null || files.length == 0; 82 | } else { 83 | return file.length() == 0; 84 | } 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/FalseFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | 22 | /** 23 | * A file filter that always returns false. 24 | * 25 | * @since 1.0 26 | * @version $Id$ 27 | * 28 | * @see FileFilterUtils#falseFileFilter() 29 | */ 30 | public class FalseFileFilter implements IOFileFilter, Serializable { 31 | 32 | private static final long serialVersionUID = 6210271677940926200L; 33 | /** 34 | * Singleton instance of false filter. 35 | * @since 1.3 36 | */ 37 | public static final IOFileFilter FALSE = new FalseFileFilter(); 38 | /** 39 | * Singleton instance of false filter. 40 | * Please use the identical FalseFileFilter.FALSE constant. 41 | * The new name is more JDK 1.5 friendly as it doesn't clash with other 42 | * values when using static imports. 43 | */ 44 | public static final IOFileFilter INSTANCE = FALSE; 45 | 46 | /** 47 | * Restrictive constructor. 48 | */ 49 | protected FalseFileFilter() { 50 | } 51 | 52 | /** 53 | * Returns false. 54 | * 55 | * @param file the file to check (ignored) 56 | * @return false 57 | */ 58 | @Override 59 | public boolean accept(final File file) { 60 | return false; 61 | } 62 | 63 | /** 64 | * Returns false. 65 | * 66 | * @param dir the directory to check (ignored) 67 | * @param name the filename (ignored) 68 | * @return false 69 | */ 70 | @Override 71 | public boolean accept(final File dir, final String name) { 72 | return false; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/FileFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | 22 | /** 23 | * This filter accepts Files that are files (not directories). 24 | *

25 | * For example, here is how to print out a list of the real files 26 | * within the current directory: 27 | * 28 | *

29 |  * File dir = new File(".");
30 |  * String[] files = dir.list( FileFileFilter.FILE );
31 |  * for ( int i = 0; i < files.length; i++ ) {
32 |  *     System.out.println(files[i]);
33 |  * }
34 |  * 
35 | * 36 | * @since 1.3 37 | * @version $Id$ 38 | * @see FileFilterUtils#fileFileFilter() 39 | */ 40 | public class FileFileFilter extends AbstractFileFilter implements Serializable { 41 | 42 | private static final long serialVersionUID = 5345244090827540862L; 43 | /** Singleton instance of file filter */ 44 | public static final IOFileFilter FILE = new FileFileFilter(); 45 | 46 | /** 47 | * Restrictive constructor. 48 | */ 49 | protected FileFileFilter() { 50 | } 51 | 52 | /** 53 | * Checks to see if the file is a file. 54 | * 55 | * @param file the File to check 56 | * @return true if the file is a file 57 | */ 58 | @Override 59 | public boolean accept(final File file) { 60 | return file.isFile(); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/HiddenFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | 22 | /** 23 | * This filter accepts Files that are hidden. 24 | *

25 | * Example, showing how to print out a list of the 26 | * current directory's hidden files: 27 | * 28 | *

29 |  * File dir = new File(".");
30 |  * String[] files = dir.list( HiddenFileFilter.HIDDEN );
31 |  * for ( int i = 0; i < files.length; i++ ) {
32 |  *     System.out.println(files[i]);
33 |  * }
34 |  * 
35 | * 36 | *

37 | * Example, showing how to print out a list of the 38 | * current directory's visible (i.e. not hidden) files: 39 | * 40 | *

41 |  * File dir = new File(".");
42 |  * String[] files = dir.list( HiddenFileFilter.VISIBLE );
43 |  * for ( int i = 0; i < files.length; i++ ) {
44 |  *     System.out.println(files[i]);
45 |  * }
46 |  * 
47 | * 48 | * @since 1.3 49 | * @version $Id$ 50 | */ 51 | public class HiddenFileFilter extends AbstractFileFilter implements Serializable { 52 | 53 | private static final long serialVersionUID = 8930842316112759062L; 54 | 55 | /** Singleton instance of hidden filter */ 56 | public static final IOFileFilter HIDDEN = new HiddenFileFilter(); 57 | 58 | /** Singleton instance of visible filter */ 59 | public static final IOFileFilter VISIBLE = new NotFileFilter(HIDDEN); 60 | 61 | /** 62 | * Restrictive constructor. 63 | */ 64 | protected HiddenFileFilter() { 65 | } 66 | 67 | /** 68 | * Checks to see if the file is hidden. 69 | * 70 | * @param file the File to check 71 | * @return {@code true} if the file is 72 | * hidden, otherwise {@code false}. 73 | */ 74 | @Override 75 | public boolean accept(final File file) { 76 | return file.isHidden(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/IOFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.FileFilter; 21 | import java.io.FilenameFilter; 22 | 23 | /** 24 | * An interface which brings the FileFilter and FilenameFilter 25 | * interfaces together. 26 | * 27 | * @since 1.0 28 | * @version $Id$ 29 | */ 30 | public interface IOFileFilter extends FileFilter, FilenameFilter { 31 | 32 | /** 33 | * Checks to see if the File should be accepted by this filter. 34 | *

35 | * Defined in {@link java.io.FileFilter}. 36 | * 37 | * @param file the File to check 38 | * @return true if this file matches the test 39 | */ 40 | @Override 41 | boolean accept(File file); 42 | 43 | /** 44 | * Checks to see if the File should be accepted by this filter. 45 | *

46 | * Defined in {@link java.io.FilenameFilter}. 47 | * 48 | * @param dir the directory File to check 49 | * @param name the filename within the directory to check 50 | * @return true if this file matches the test 51 | */ 52 | @Override 53 | boolean accept(File dir, String name); 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/NotFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | 22 | /** 23 | * This filter produces a logical NOT of the filters specified. 24 | * 25 | * @since 1.0 26 | * @version $Id$ 27 | * @see FileFilterUtils#notFileFilter(IOFileFilter) 28 | */ 29 | public class NotFileFilter extends AbstractFileFilter implements Serializable { 30 | 31 | private static final long serialVersionUID = 6131563330944994230L; 32 | /** The filter */ 33 | private final IOFileFilter filter; 34 | 35 | /** 36 | * Constructs a new file filter that NOTs the result of another filter. 37 | * 38 | * @param filter the filter, must not be null 39 | * @throws IllegalArgumentException if the filter is null 40 | */ 41 | public NotFileFilter(final IOFileFilter filter) { 42 | if (filter == null) { 43 | throw new IllegalArgumentException("The filter must not be null"); 44 | } 45 | this.filter = filter; 46 | } 47 | 48 | /** 49 | * Returns the logical NOT of the underlying filter's return value for the same File. 50 | * 51 | * @param file the File to check 52 | * @return true if the filter returns false 53 | */ 54 | @Override 55 | public boolean accept(final File file) { 56 | return ! filter.accept(file); 57 | } 58 | 59 | /** 60 | * Returns the logical NOT of the underlying filter's return value for the same arguments. 61 | * 62 | * @param file the File directory 63 | * @param name the filename 64 | * @return true if the filter returns false 65 | */ 66 | @Override 67 | public boolean accept(final File file, final String name) { 68 | return ! filter.accept(file, name); 69 | } 70 | 71 | /** 72 | * Provide a String representation of this file filter. 73 | * 74 | * @return a String representation 75 | */ 76 | @Override 77 | public String toString() { 78 | return super.toString() + "(" + filter.toString() + ")"; 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/RegexFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | import java.util.regex.Pattern; 22 | 23 | import org.apache.commons.io.IOCase; 24 | 25 | /** 26 | * Filters files using supplied regular expression(s). 27 | *

28 | * See java.util.regex.Pattern for regex matching rules 29 | *

30 | * 31 | *

32 | * e.g. 33 | *

 34 |  * File dir = new File(".");
 35 |  * FileFilter fileFilter = new RegexFileFilter("^.*[tT]est(-\\d+)?\\.java$");
 36 |  * File[] files = dir.listFiles(fileFilter);
 37 |  * for (int i = 0; i < files.length; i++) {
 38 |  *   System.out.println(files[i]);
 39 |  * }
 40 |  * 
41 | * 42 | * @since 1.4 43 | */ 44 | public class RegexFileFilter extends AbstractFileFilter implements Serializable { 45 | 46 | private static final long serialVersionUID = 4269646126155225062L; 47 | /** The regular expression pattern that will be used to match filenames */ 48 | private final Pattern pattern; 49 | 50 | /** 51 | * Construct a new regular expression filter. 52 | * 53 | * @param pattern regular string expression to match 54 | * @throws IllegalArgumentException if the pattern is null 55 | */ 56 | public RegexFileFilter(final String pattern) { 57 | if (pattern == null) { 58 | throw new IllegalArgumentException("Pattern is missing"); 59 | } 60 | 61 | this.pattern = Pattern.compile(pattern); 62 | } 63 | 64 | /** 65 | * Construct a new regular expression filter with the specified flags case sensitivity. 66 | * 67 | * @param pattern regular string expression to match 68 | * @param caseSensitivity how to handle case sensitivity, null means case-sensitive 69 | * @throws IllegalArgumentException if the pattern is null 70 | */ 71 | public RegexFileFilter(final String pattern, final IOCase caseSensitivity) { 72 | if (pattern == null) { 73 | throw new IllegalArgumentException("Pattern is missing"); 74 | } 75 | int flags = 0; 76 | if (caseSensitivity != null && !caseSensitivity.isCaseSensitive()) { 77 | flags = Pattern.CASE_INSENSITIVE; 78 | } 79 | this.pattern = Pattern.compile(pattern, flags); 80 | } 81 | 82 | /** 83 | * Construct a new regular expression filter with the specified flags. 84 | * 85 | * @param pattern regular string expression to match 86 | * @param flags pattern flags - e.g. {@link Pattern#CASE_INSENSITIVE} 87 | * @throws IllegalArgumentException if the pattern is null 88 | */ 89 | public RegexFileFilter(final String pattern, final int flags) { 90 | if (pattern == null) { 91 | throw new IllegalArgumentException("Pattern is missing"); 92 | } 93 | this.pattern = Pattern.compile(pattern, flags); 94 | } 95 | 96 | /** 97 | * Construct a new regular expression filter for a compiled regular expression 98 | * 99 | * @param pattern regular expression to match 100 | * @throws IllegalArgumentException if the pattern is null 101 | */ 102 | public RegexFileFilter(final Pattern pattern) { 103 | if (pattern == null) { 104 | throw new IllegalArgumentException("Pattern is missing"); 105 | } 106 | 107 | this.pattern = pattern; 108 | } 109 | 110 | /** 111 | * Checks to see if the filename matches one of the regular expressions. 112 | * 113 | * @param dir the file directory (ignored) 114 | * @param name the filename 115 | * @return true if the filename matches one of the regular expressions 116 | */ 117 | @Override 118 | public boolean accept(final File dir, final String name) { 119 | return pattern.matcher(name).matches(); 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/SizeFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | 22 | /** 23 | * Filters files based on size, can filter either smaller files or 24 | * files equal to or larger than a given threshold. 25 | *

26 | * For example, to print all files and directories in the 27 | * current directory whose size is greater than 1 MB: 28 | * 29 | *

 30 |  * File dir = new File(".");
 31 |  * String[] files = dir.list( new SizeFileFilter(1024 * 1024) );
 32 |  * for ( int i = 0; i < files.length; i++ ) {
 33 |  *     System.out.println(files[i]);
 34 |  * }
 35 |  * 
36 | * 37 | * @since 1.2 38 | * @see FileFilterUtils#sizeFileFilter(long) 39 | * @see FileFilterUtils#sizeFileFilter(long, boolean) 40 | * @see FileFilterUtils#sizeRangeFileFilter(long, long) 41 | */ 42 | public class SizeFileFilter extends AbstractFileFilter implements Serializable { 43 | 44 | private static final long serialVersionUID = 7388077430788600069L; 45 | /** The size threshold. */ 46 | private final long size; 47 | /** Whether the files accepted will be larger or smaller. */ 48 | private final boolean acceptLarger; 49 | 50 | /** 51 | * Constructs a new size file filter for files equal to or 52 | * larger than a certain size. 53 | * 54 | * @param size the threshold size of the files 55 | * @throws IllegalArgumentException if the size is negative 56 | */ 57 | public SizeFileFilter(final long size) { 58 | this(size, true); 59 | } 60 | 61 | /** 62 | * Constructs a new size file filter for files based on a certain size 63 | * threshold. 64 | * 65 | * @param size the threshold size of the files 66 | * @param acceptLarger if true, files equal to or larger are accepted, 67 | * otherwise smaller ones (but not equal to) 68 | * @throws IllegalArgumentException if the size is negative 69 | */ 70 | public SizeFileFilter(final long size, final boolean acceptLarger) { 71 | if (size < 0) { 72 | throw new IllegalArgumentException("The size must be non-negative"); 73 | } 74 | this.size = size; 75 | this.acceptLarger = acceptLarger; 76 | } 77 | 78 | //----------------------------------------------------------------------- 79 | /** 80 | * Checks to see if the size of the file is favorable. 81 | *

82 | * If size equals threshold and smaller files are required, 83 | * file IS NOT selected. 84 | * If size equals threshold and larger files are required, 85 | * file IS selected. 86 | * 87 | * @param file the File to check 88 | * @return true if the filename matches 89 | */ 90 | @Override 91 | public boolean accept(final File file) { 92 | final boolean smaller = file.length() < size; 93 | return acceptLarger ? !smaller : smaller; 94 | } 95 | 96 | /** 97 | * Provide a String representation of this file filter. 98 | * 99 | * @return a String representation 100 | */ 101 | @Override 102 | public String toString() { 103 | final String condition = acceptLarger ? ">=" : "<"; 104 | return super.toString() + "(" + condition + size + ")"; 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/TrueFileFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.filefilter; 18 | 19 | import java.io.File; 20 | import java.io.Serializable; 21 | 22 | /** 23 | * A file filter that always returns true. 24 | * 25 | * @since 1.0 26 | * @version $Id$ 27 | * @see FileFilterUtils#trueFileFilter() 28 | */ 29 | public class TrueFileFilter implements IOFileFilter, Serializable { 30 | 31 | private static final long serialVersionUID = 8782512160909720199L; 32 | /** 33 | * Singleton instance of true filter. 34 | * @since 1.3 35 | */ 36 | public static final IOFileFilter TRUE = new TrueFileFilter(); 37 | /** 38 | * Singleton instance of true filter. 39 | * Please use the identical TrueFileFilter.TRUE constant. 40 | * The new name is more JDK 1.5 friendly as it doesn't clash with other 41 | * values when using static imports. 42 | */ 43 | public static final IOFileFilter INSTANCE = TRUE; 44 | 45 | /** 46 | * Restrictive constructor. 47 | */ 48 | protected TrueFileFilter() { 49 | } 50 | 51 | /** 52 | * Returns true. 53 | * 54 | * @param file the file to check (ignored) 55 | * @return true 56 | */ 57 | @Override 58 | public boolean accept(final File file) { 59 | return true; 60 | } 61 | 62 | /** 63 | * Returns true. 64 | * 65 | * @param dir the directory to check (ignored) 66 | * @param name the filename (ignored) 67 | * @return true 68 | */ 69 | @Override 70 | public boolean accept(final File dir, final String name) { 71 | return true; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/filefilter/package.html: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 |

This package defines an interface (IOFileFilter) that combines both 21 | {@link java.io.FileFilter} and {@link java.io.FilenameFilter}. Besides 22 | that the package offers a series of ready-to-use implementations of the 23 | IOFileFilter interface including implementation that allow you to combine 24 | other such filters.

25 |

These filter can be used to list files or in {@link java.awt.FileDialog}, 26 | for example.

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 |
There are a number of 'primitive' filters:
DirectoryFilterOnly accept directories
PrefixFileFilterFilter based on a prefix
SuffixFileFilterFilter based on a suffix
NameFileFilterFilter based on a filename
WildcardFileFilterFilter based on wildcards
AgeFileFilterFilter based on last modified time of file
SizeFileFilterFilter based on file size
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 |
And there are five 'boolean' filters:
TrueFileFilterAccept all files
FalseFileFilterAccept no files
NotFileFilterApplies a logical NOT to an existing filter
AndFileFilterCombines two filters using a logical AND
OrFileFilterCombines two filter using a logical OR
86 | 87 |

These boolean FilenameFilters can be nested, to allow arbitrary expressions. 88 | For example, here is how one could print all non-directory files in the 89 | current directory, starting with "A", and ending in ".java" or ".class":

90 | 91 |
 92 |   File dir = new File(".");
 93 |   String[] files = dir.list( 
 94 |     new AndFileFilter(
 95 |       new AndFileFilter(
 96 |         new PrefixFileFilter("A"),
 97 |         new OrFileFilter(
 98 |           new SuffixFileFilter(".class"),
 99 |           new SuffixFileFilter(".java")
100 |         )
101 |       ),
102 |       new NotFileFilter(
103 |         new DirectoryFileFilter()
104 |       )
105 |     )
106 |   );
107 |   for ( int i=0; i<files.length; i++ ) {
108 |     System.out.println(files[i]);
109 |   }
110 | 
111 | 112 |

This package also contains a utility class: 113 | FileFilterUtils. It allows you to use all 114 | file filters without having to put them in the import section. Here's how the 115 | above example will look using FileFilterUtils:

116 |
117 |   File dir = new File(".");
118 |   String[] files = dir.list( 
119 |     FileFilterUtils.andFileFilter(
120 |       FileFilterUtils.andFileFilter(
121 |         FileFilterUtils.prefixFileFilter("A"),
122 |         FileFilterUtils.orFileFilter(
123 |           FileFilterUtils.suffixFileFilter(".class"),
124 |           FileFilterUtils.suffixFileFilter(".java")
125 |         )
126 |       ),
127 |       FileFilterUtils.notFileFilter(
128 |         FileFilterUtils.directoryFileFilter()
129 |       )
130 |     )
131 |   );
132 |   for ( int i=0; i<files.length; i++ ) {
133 |     System.out.println(files[i]);
134 |   }
135 | 
136 |

There are a few other goodies in that class so please have a look at the 137 | documentation in detail.

138 | 139 | 140 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/AutoCloseInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | import static org.apache.commons.io.IOUtils.EOF; 20 | 21 | import java.io.IOException; 22 | import java.io.InputStream; 23 | 24 | /** 25 | * Proxy stream that closes and discards the underlying stream as soon as the 26 | * end of input has been reached or when the stream is explicitly closed. 27 | * Not even a reference to the underlying stream is kept after it has been 28 | * closed, so any allocated in-memory buffers can be freed even if the 29 | * client application still keeps a reference to the proxy stream. 30 | *

31 | * This class is typically used to release any resources related to an open 32 | * stream as soon as possible even if the client application (by not explicitly 33 | * closing the stream when no longer needed) or the underlying stream (by not 34 | * releasing resources once the last byte has been read) do not do that. 35 | * 36 | * @since 1.4 37 | */ 38 | public class AutoCloseInputStream extends ProxyInputStream { 39 | 40 | /** 41 | * Creates an automatically closing proxy for the given input stream. 42 | * 43 | * @param in underlying input stream 44 | */ 45 | public AutoCloseInputStream(final InputStream in) { 46 | super(in); 47 | } 48 | 49 | /** 50 | * Closes the underlying input stream and replaces the reference to it 51 | * with a {@link ClosedInputStream} instance. 52 | *

53 | * This method is automatically called by the read methods when the end 54 | * of input has been reached. 55 | *

56 | * Note that it is safe to call this method any number of times. The original 57 | * underlying input stream is closed and discarded only once when this 58 | * method is first called. 59 | * 60 | * @throws IOException if the underlying input stream can not be closed 61 | */ 62 | @Override 63 | public void close() throws IOException { 64 | in.close(); 65 | in = new ClosedInputStream(); 66 | } 67 | 68 | /** 69 | * Automatically closes the stream if the end of stream was reached. 70 | * 71 | * @param n number of bytes read, or -1 if no more bytes are available 72 | * @throws IOException if the stream could not be closed 73 | * @since 2.0 74 | */ 75 | @Override 76 | protected void afterRead(final int n) throws IOException { 77 | if (n == EOF) { 78 | close(); 79 | } 80 | } 81 | 82 | /** 83 | * Ensures that the stream is closed before it gets garbage-collected. 84 | * As mentioned in {@link #close()}, this is a no-op if the stream has 85 | * already been closed. 86 | * @throws Throwable if an error occurs 87 | */ 88 | @Override 89 | protected void finalize() throws Throwable { 90 | close(); 91 | super.finalize(); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/BrokenInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | import java.io.IOException; 20 | import java.io.InputStream; 21 | 22 | /** 23 | * Broken input stream. This stream always throws an {@link IOException} from 24 | * all the {@link InputStream} methods where the exception is declared. 25 | *

26 | * This class is mostly useful for testing error handling in code that uses an 27 | * input stream. 28 | * 29 | * @since 2.0 30 | */ 31 | public class BrokenInputStream extends InputStream { 32 | 33 | /** 34 | * The exception that is thrown by all methods of this class. 35 | */ 36 | private final IOException exception; 37 | 38 | /** 39 | * Creates a new stream that always throws the given exception. 40 | * 41 | * @param exception the exception to be thrown 42 | */ 43 | public BrokenInputStream(final IOException exception) { 44 | this.exception = exception; 45 | } 46 | 47 | /** 48 | * Creates a new stream that always throws an {@link IOException} 49 | */ 50 | public BrokenInputStream() { 51 | this(new IOException("Broken input stream")); 52 | } 53 | 54 | /** 55 | * Throws the configured exception. 56 | * 57 | * @return nothing 58 | * @throws IOException always thrown 59 | */ 60 | @Override 61 | public int read() throws IOException { 62 | throw exception; 63 | } 64 | 65 | /** 66 | * Throws the configured exception. 67 | * 68 | * @return nothing 69 | * @throws IOException always thrown 70 | */ 71 | @Override 72 | public int available() throws IOException { 73 | throw exception; 74 | } 75 | 76 | /** 77 | * Throws the configured exception. 78 | * 79 | * @param n ignored 80 | * @return nothing 81 | * @throws IOException always thrown 82 | */ 83 | @Override 84 | public long skip(final long n) throws IOException { 85 | throw exception; 86 | } 87 | 88 | /** 89 | * Throws the configured exception. 90 | * 91 | * @throws IOException always thrown 92 | */ 93 | @Override 94 | public synchronized void reset() throws IOException { 95 | throw exception; 96 | } 97 | 98 | /** 99 | * Throws the configured exception. 100 | * 101 | * @throws IOException always thrown 102 | */ 103 | @Override 104 | public void close() throws IOException { 105 | throw exception; 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/ClassLoaderObjectInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | import java.io.IOException; 20 | import java.io.InputStream; 21 | import java.io.ObjectInputStream; 22 | import java.io.ObjectStreamClass; 23 | import java.io.StreamCorruptedException; 24 | import java.lang.reflect.Proxy; 25 | 26 | /** 27 | * A special ObjectInputStream that loads a class based on a specified 28 | * ClassLoader rather than the system default. 29 | *

30 | * This is useful in dynamic container environments. 31 | * 32 | * @since 1.1 33 | */ 34 | public class ClassLoaderObjectInputStream extends ObjectInputStream { 35 | 36 | /** The class loader to use. */ 37 | private final ClassLoader classLoader; 38 | 39 | /** 40 | * Constructs a new ClassLoaderObjectInputStream. 41 | * 42 | * @param classLoader the ClassLoader from which classes should be loaded 43 | * @param inputStream the InputStream to work on 44 | * @throws IOException in case of an I/O error 45 | * @throws StreamCorruptedException if the stream is corrupted 46 | */ 47 | public ClassLoaderObjectInputStream( 48 | final ClassLoader classLoader, final InputStream inputStream) 49 | throws IOException, StreamCorruptedException { 50 | super(inputStream); 51 | this.classLoader = classLoader; 52 | } 53 | 54 | /** 55 | * Resolve a class specified by the descriptor using the 56 | * specified ClassLoader or the super ClassLoader. 57 | * 58 | * @param objectStreamClass descriptor of the class 59 | * @return the Class object described by the ObjectStreamClass 60 | * @throws IOException in case of an I/O error 61 | * @throws ClassNotFoundException if the Class cannot be found 62 | */ 63 | @Override 64 | protected Class resolveClass(final ObjectStreamClass objectStreamClass) 65 | throws IOException, ClassNotFoundException { 66 | 67 | try { 68 | return Class.forName(objectStreamClass.getName(), false, classLoader); 69 | } catch (final ClassNotFoundException cnfe) { 70 | // delegate to super class loader which can resolve primitives 71 | return super.resolveClass(objectStreamClass); 72 | } 73 | } 74 | 75 | /** 76 | * Create a proxy class that implements the specified interfaces using 77 | * the specified ClassLoader or the super ClassLoader. 78 | * 79 | * @param interfaces the interfaces to implement 80 | * @return a proxy class implementing the interfaces 81 | * @throws IOException in case of an I/O error 82 | * @throws ClassNotFoundException if the Class cannot be found 83 | * @see java.io.ObjectInputStream#resolveProxyClass(java.lang.String[]) 84 | * @since 2.1 85 | */ 86 | @Override 87 | protected Class resolveProxyClass(final String[] interfaces) throws IOException, 88 | ClassNotFoundException { 89 | final Class[] interfaceClasses = new Class[interfaces.length]; 90 | for (int i = 0; i < interfaces.length; i++) { 91 | interfaceClasses[i] = Class.forName(interfaces[i], false, classLoader); 92 | } 93 | try { 94 | return Proxy.getProxyClass(classLoader, interfaceClasses); 95 | } catch (final IllegalArgumentException e) { 96 | return super.resolveProxyClass(interfaces); 97 | } 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/CloseShieldInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | import java.io.InputStream; 20 | 21 | /** 22 | * Proxy stream that prevents the underlying input stream from being closed. 23 | *

24 | * This class is typically used in cases where an input stream needs to be 25 | * passed to a component that wants to explicitly close the stream even if 26 | * more input would still be available to other components. 27 | * 28 | * @since 1.4 29 | */ 30 | public class CloseShieldInputStream extends ProxyInputStream { 31 | 32 | /** 33 | * Creates a proxy that shields the given input stream from being 34 | * closed. 35 | * 36 | * @param in underlying input stream 37 | */ 38 | public CloseShieldInputStream(final InputStream in) { 39 | super(in); 40 | } 41 | 42 | /** 43 | * Replaces the underlying input stream with a {@link ClosedInputStream} 44 | * sentinel. The original input stream will remain open, but this proxy 45 | * will appear closed. 46 | */ 47 | @Override 48 | public void close() { 49 | in = new ClosedInputStream(); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/ClosedInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | import static org.apache.commons.io.IOUtils.EOF; 20 | 21 | import java.io.InputStream; 22 | 23 | /** 24 | * Closed input stream. This stream returns EOF to all attempts to read 25 | * something from the stream. 26 | *

27 | * Typically uses of this class include testing for corner cases in methods 28 | * that accept input streams and acting as a sentinel value instead of a 29 | * {@code null} input stream. 30 | * 31 | * @since 1.4 32 | */ 33 | public class ClosedInputStream extends InputStream { 34 | 35 | /** 36 | * A singleton. 37 | */ 38 | public static final ClosedInputStream CLOSED_INPUT_STREAM = new ClosedInputStream(); 39 | 40 | /** 41 | * Returns -1 to indicate that the stream is closed. 42 | * 43 | * @return always -1 44 | */ 45 | @Override 46 | public int read() { 47 | return EOF; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/CountingInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | import static org.apache.commons.io.IOUtils.EOF; 20 | 21 | import java.io.IOException; 22 | import java.io.InputStream; 23 | 24 | /** 25 | * A decorating input stream that counts the number of bytes that have passed 26 | * through the stream so far. 27 | *

28 | * A typical use case would be during debugging, to ensure that data is being 29 | * read as expected. 30 | * 31 | */ 32 | public class CountingInputStream extends ProxyInputStream { 33 | 34 | /** The count of bytes that have passed. */ 35 | private long count; 36 | 37 | /** 38 | * Constructs a new CountingInputStream. 39 | * 40 | * @param in the InputStream to delegate to 41 | */ 42 | public CountingInputStream(final InputStream in) { 43 | super(in); 44 | } 45 | 46 | //----------------------------------------------------------------------- 47 | 48 | /** 49 | * Skips the stream over the specified number of bytes, adding the skipped 50 | * amount to the count. 51 | * 52 | * @param length the number of bytes to skip 53 | * @return the actual number of bytes skipped 54 | * @throws IOException if an I/O error occurs 55 | * @see java.io.InputStream#skip(long) 56 | */ 57 | @Override 58 | public synchronized long skip(final long length) throws IOException { 59 | final long skip = super.skip(length); 60 | this.count += skip; 61 | return skip; 62 | } 63 | 64 | /** 65 | * Adds the number of read bytes to the count. 66 | * 67 | * @param n number of bytes read, or -1 if no more bytes are available 68 | * @since 2.0 69 | */ 70 | @Override 71 | protected synchronized void afterRead(final int n) { 72 | if (n != EOF) { 73 | this.count += n; 74 | } 75 | } 76 | 77 | //----------------------------------------------------------------------- 78 | /** 79 | * The number of bytes that have passed through this stream. 80 | *

81 | * NOTE: From v1.3 this method throws an ArithmeticException if the 82 | * count is greater than can be expressed by an int. 83 | * See {@link #getByteCount()} for a method using a long. 84 | * 85 | * @return the number of bytes accumulated 86 | * @throws ArithmeticException if the byte count is too large 87 | */ 88 | public int getCount() { 89 | final long result = getByteCount(); 90 | if (result > Integer.MAX_VALUE) { 91 | throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int"); 92 | } 93 | return (int) result; 94 | } 95 | 96 | /** 97 | * Set the byte count back to 0. 98 | *

99 | * NOTE: From v1.3 this method throws an ArithmeticException if the 100 | * count is greater than can be expressed by an int. 101 | * See {@link #resetByteCount()} for a method using a long. 102 | * 103 | * @return the count previous to resetting 104 | * @throws ArithmeticException if the byte count is too large 105 | */ 106 | public int resetCount() { 107 | final long result = resetByteCount(); 108 | if (result > Integer.MAX_VALUE) { 109 | throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int"); 110 | } 111 | return (int) result; 112 | } 113 | 114 | /** 115 | * The number of bytes that have passed through this stream. 116 | *

117 | * NOTE: This method is an alternative for getCount() 118 | * and was added because that method returns an integer which will 119 | * result in incorrect count for files over 2GB. 120 | * 121 | * @return the number of bytes accumulated 122 | * @since 1.3 123 | */ 124 | public synchronized long getByteCount() { 125 | return this.count; 126 | } 127 | 128 | /** 129 | * Set the byte count back to 0. 130 | *

131 | * NOTE: This method is an alternative for resetCount() 132 | * and was added because that method returns an integer which will 133 | * result in incorrect count for files over 2GB. 134 | * 135 | * @return the count previous to resetting 136 | * @since 1.3 137 | */ 138 | public synchronized long resetByteCount() { 139 | final long tmp = this.count; 140 | this.count = 0; 141 | return tmp; 142 | } 143 | 144 | } 145 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/DemuxInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | import static org.apache.commons.io.IOUtils.EOF; 20 | 21 | import java.io.IOException; 22 | import java.io.InputStream; 23 | 24 | /** 25 | * Data written to this stream is forwarded to a stream that has been associated 26 | * with this thread. 27 | * 28 | */ 29 | public class DemuxInputStream 30 | extends InputStream 31 | { 32 | private final InheritableThreadLocal m_streams = new InheritableThreadLocal<>(); 33 | 34 | /** 35 | * Bind the specified stream to the current thread. 36 | * 37 | * @param input the stream to bind 38 | * @return the InputStream that was previously active 39 | */ 40 | public InputStream bindStream( final InputStream input ) 41 | { 42 | final InputStream oldValue = m_streams.get(); 43 | m_streams.set( input ); 44 | return oldValue; 45 | } 46 | 47 | /** 48 | * Closes stream associated with current thread. 49 | * 50 | * @throws IOException if an error occurs 51 | */ 52 | @Override 53 | public void close() 54 | throws IOException 55 | { 56 | final InputStream input = m_streams.get(); 57 | if( null != input ) 58 | { 59 | input.close(); 60 | } 61 | } 62 | 63 | /** 64 | * Read byte from stream associated with current thread. 65 | * 66 | * @return the byte read from stream 67 | * @throws IOException if an error occurs 68 | */ 69 | @Override 70 | public int read() 71 | throws IOException 72 | { 73 | final InputStream input = m_streams.get(); 74 | if( null != input ) 75 | { 76 | return input.read(); 77 | } 78 | else 79 | { 80 | return EOF; 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/InfiniteCircularInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | import java.io.InputStream; 20 | 21 | /** 22 | * 23 | * An {@link InputStream} that infinitely repeats provided bytes. 24 | *

25 | * Closing a InfiniteCircularInputStream has no effect. The methods in 26 | * this class can be called after the stream has been closed without generating 27 | * an IOException. 28 | * 29 | */ 30 | public class InfiniteCircularInputStream extends InputStream { 31 | 32 | final private byte[] repeatedContent; 33 | private int position = -1; 34 | 35 | /** 36 | * Creates a InfiniteCircularStream from the specified array of chars. 37 | * 38 | * @param repeatedContent 39 | * Input buffer to be repeated (not copied) 40 | */ 41 | public InfiniteCircularInputStream(final byte[] repeatedContent) { 42 | this.repeatedContent = repeatedContent; 43 | } 44 | 45 | @Override 46 | public int read() { 47 | position = (position + 1) % repeatedContent.length; 48 | return repeatedContent[position] & 0xff; // copied from 49 | // java.io.ByteArrayInputStream.read() 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/MessageDigestCalculatingInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | import java.io.IOException; 20 | import java.io.InputStream; 21 | import java.security.MessageDigest; 22 | import java.security.NoSuchAlgorithmException; 23 | 24 | 25 | /** 26 | * This class is an example for using an {@link ObservableInputStream}. It 27 | * creates its own {@link org.apache.commons.io.input.ObservableInputStream.Observer}, 28 | * which calculates a checksum using a MessageDigest, for example an MD5 sum. 29 | * Note: Neither {@link ObservableInputStream}, nor {@link MessageDigest}, 30 | * are thread safe. So is {@link MessageDigestCalculatingInputStream}. 31 | */ 32 | public class MessageDigestCalculatingInputStream extends ObservableInputStream { 33 | 34 | /** 35 | * Maintains the message digest. 36 | */ 37 | public static class MessageDigestMaintainingObserver extends Observer { 38 | private final MessageDigest md; 39 | 40 | /** 41 | * Creates an MessageDigestMaintainingObserver for the given MessageDigest. 42 | * @param pMd the message digest to use 43 | */ 44 | public MessageDigestMaintainingObserver(final MessageDigest pMd) { 45 | md = pMd; 46 | } 47 | 48 | @Override 49 | void data(final int pByte) throws IOException { 50 | md.update((byte) pByte); 51 | } 52 | 53 | @Override 54 | void data(final byte[] pBuffer, final int pOffset, final int pLength) throws IOException { 55 | md.update(pBuffer, pOffset, pLength); 56 | } 57 | } 58 | 59 | private final MessageDigest messageDigest; 60 | 61 | /** Creates a new instance, which calculates a signature on the given stream, 62 | * using the given {@link MessageDigest}. 63 | * @param pStream the stream to calculate the message digest for 64 | * @param pDigest the message digest to use 65 | */ 66 | public MessageDigestCalculatingInputStream(final InputStream pStream, final MessageDigest pDigest) { 67 | super(pStream); 68 | messageDigest = pDigest; 69 | add(new MessageDigestMaintainingObserver(pDigest)); 70 | } 71 | 72 | /** Creates a new instance, which calculates a signature on the given stream, 73 | * using a {@link MessageDigest} with the given algorithm. 74 | * @param pStream the stream to calculate the message digest for 75 | * @param pAlgorithm the name of the algorithm to use 76 | * @throws NoSuchAlgorithmException if no Provider supports a MessageDigestSpi implementation for the specified algorithm. 77 | */ 78 | public MessageDigestCalculatingInputStream(final InputStream pStream, final String pAlgorithm) throws NoSuchAlgorithmException { 79 | this(pStream, MessageDigest.getInstance(pAlgorithm)); 80 | } 81 | 82 | /** Creates a new instance, which calculates a signature on the given stream, 83 | * using a {@link MessageDigest} with the "MD5" algorithm. 84 | * @param pStream the stream to calculate the message digest for 85 | * @throws NoSuchAlgorithmException if no Provider supports a MessageDigestSpi implementation for the specified algorithm. 86 | */ 87 | public MessageDigestCalculatingInputStream(final InputStream pStream) throws NoSuchAlgorithmException { 88 | this(pStream, MessageDigest.getInstance("MD5")); 89 | } 90 | 91 | /** Returns the {@link MessageDigest}, which is being used for generating the 92 | * checksum. 93 | * Note: The checksum will only reflect the data, which has been read so far. 94 | * This is probably not, what you expect. Make sure, that the complete data has been 95 | * read, if that is what you want. The easiest way to do so is by invoking 96 | * {@link #consume()}. 97 | * @return the message digest used 98 | */ 99 | public MessageDigest getMessageDigest() { 100 | return messageDigest; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/TaggedInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | import java.io.IOException; 20 | import java.io.InputStream; 21 | import java.io.Serializable; 22 | import java.util.UUID; 23 | 24 | import org.apache.commons.io.TaggedIOException; 25 | 26 | /** 27 | * An input stream decorator that tags potential exceptions so that the 28 | * stream that caused the exception can easily be identified. This is 29 | * done by using the {@link TaggedIOException} class to wrap all thrown 30 | * {@link IOException}s. See below for an example of using this class. 31 | *

 32 |  * TaggedInputStream stream = new TaggedInputStream(...);
 33 |  * try {
 34 |  *     // Processing that may throw an IOException either from this stream
 35 |  *     // or from some other IO activity like temporary files, etc.
 36 |  *     processStream(stream);
 37 |  * } catch (IOException e) {
 38 |  *     if (stream.isCauseOf(e)) {
 39 |  *         // The exception was caused by this stream.
 40 |  *         // Use e.getCause() to get the original exception.
 41 |  *     } else {
 42 |  *         // The exception was caused by something else.
 43 |  *     }
 44 |  * }
 45 |  * 
46 | *

47 | * Alternatively, the {@link #throwIfCauseOf(Throwable)} method can be 48 | * used to let higher levels of code handle the exception caused by this 49 | * stream while other processing errors are being taken care of at this 50 | * lower level. 51 | *

 52 |  * TaggedInputStream stream = new TaggedInputStream(...);
 53 |  * try {
 54 |  *     processStream(stream);
 55 |  * } catch (IOException e) {
 56 |  *     stream.throwIfCauseOf(e);
 57 |  *     // ... or process the exception that was caused by something else
 58 |  * }
 59 |  * 
60 | * 61 | * @see TaggedIOException 62 | * @since 2.0 63 | */ 64 | public class TaggedInputStream extends ProxyInputStream { 65 | 66 | /** 67 | * The unique tag associated with exceptions from stream. 68 | */ 69 | private final Serializable tag = UUID.randomUUID(); 70 | 71 | /** 72 | * Creates a tagging decorator for the given input stream. 73 | * 74 | * @param proxy input stream to be decorated 75 | */ 76 | public TaggedInputStream(final InputStream proxy) { 77 | super(proxy); 78 | } 79 | 80 | /** 81 | * Tests if the given exception was caused by this stream. 82 | * 83 | * @param exception an exception 84 | * @return {@code true} if the exception was thrown by this stream, 85 | * {@code false} otherwise 86 | */ 87 | public boolean isCauseOf(final Throwable exception) { 88 | return TaggedIOException.isTaggedWith(exception, tag); 89 | } 90 | 91 | /** 92 | * Re-throws the original exception thrown by this stream. This method 93 | * first checks whether the given exception is a {@link TaggedIOException} 94 | * wrapper created by this decorator, and then unwraps and throws the 95 | * original wrapped exception. Returns normally if the exception was 96 | * not thrown by this stream. 97 | * 98 | * @param throwable an exception 99 | * @throws IOException original exception, if any, thrown by this stream 100 | */ 101 | public void throwIfCauseOf(final Throwable throwable) throws IOException { 102 | TaggedIOException.throwCauseIfTaggedWith(throwable, tag); 103 | } 104 | 105 | /** 106 | * Tags any IOExceptions thrown, wrapping and re-throwing. 107 | * 108 | * @param e The IOException thrown 109 | * @throws IOException if an I/O error occurs 110 | */ 111 | @Override 112 | protected void handleIOException(final IOException e) throws IOException { 113 | throw new TaggedIOException(e, tag); 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/TailerListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | /** 20 | * Listener for events from a {@link Tailer}. 21 | * 22 | * @since 2.0 23 | */ 24 | public interface TailerListener { 25 | 26 | /** 27 | * The tailer will call this method during construction, 28 | * giving the listener a method of stopping the tailer. 29 | * @param tailer the tailer. 30 | */ 31 | void init(Tailer tailer); 32 | 33 | /** 34 | * This method is called if the tailed file is not found. 35 | *

36 | * Note: this is called from the tailer thread. 37 | */ 38 | void fileNotFound(); 39 | 40 | /** 41 | * Called if a file rotation is detected. 42 | * 43 | * This method is called before the file is reopened, and fileNotFound may 44 | * be called if the new file has not yet been created. 45 | *

46 | * Note: this is called from the tailer thread. 47 | */ 48 | void fileRotated(); 49 | 50 | /** 51 | * Handles a line from a Tailer. 52 | *

53 | * Note: this is called from the tailer thread. 54 | * @param line the line. 55 | */ 56 | void handle(String line); 57 | 58 | /** 59 | * Handles an Exception . 60 | *

61 | * Note: this is called from the tailer thread. 62 | * @param ex the exception. 63 | */ 64 | void handle(Exception ex); 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/TailerListenerAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | /** 20 | * {@link TailerListener} Adapter. 21 | * 22 | * @since 2.0 23 | */ 24 | public class TailerListenerAdapter implements TailerListener { 25 | 26 | /** 27 | * The tailer will call this method during construction, 28 | * giving the listener a method of stopping the tailer. 29 | * @param tailer the tailer. 30 | */ 31 | @Override 32 | public void init(final Tailer tailer) { 33 | } 34 | 35 | /** 36 | * This method is called if the tailed file is not found. 37 | */ 38 | @Override 39 | public void fileNotFound() { 40 | } 41 | 42 | /** 43 | * Called if a file rotation is detected. 44 | * 45 | * This method is called before the file is reopened, and fileNotFound may 46 | * be called if the new file has not yet been created. 47 | */ 48 | @Override 49 | public void fileRotated() { 50 | } 51 | 52 | /** 53 | * Handles a line from a Tailer. 54 | * @param line the line. 55 | */ 56 | @Override 57 | public void handle(final String line) { 58 | } 59 | 60 | /** 61 | * Handles an Exception . 62 | * @param ex the exception. 63 | */ 64 | @Override 65 | public void handle(final Exception ex) { 66 | } 67 | 68 | /** 69 | * Called each time the Tailer reaches the end of the file. 70 | * 71 | * Note: this is called from the tailer thread. 72 | * 73 | * Note: a future version of commons-io will pull this method up to the TailerListener interface, 74 | * for now clients must subclass this class to use this feature. 75 | * 76 | * @since 2.5 77 | */ 78 | public void endOfFileReached() { 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/UnixLineEndingInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | 23 | /** 24 | * A filtering input stream that ensures the content will have unix-style line endings, LF. 25 | * 26 | * @since 2.5 27 | */ 28 | public class UnixLineEndingInputStream extends InputStream { 29 | 30 | private boolean slashNSeen = false; 31 | 32 | private boolean slashRSeen = false; 33 | 34 | private boolean eofSeen = false; 35 | 36 | private final InputStream target; 37 | 38 | private final boolean ensureLineFeedAtEndOfFile; 39 | 40 | /** 41 | * Create an input stream that filters another stream 42 | * 43 | * @param in The input stream to wrap 44 | * @param ensureLineFeedAtEndOfFile true to ensure that the file ends with LF 45 | */ 46 | public UnixLineEndingInputStream( final InputStream in, final boolean ensureLineFeedAtEndOfFile ) { 47 | this.target = in; 48 | this.ensureLineFeedAtEndOfFile = ensureLineFeedAtEndOfFile; 49 | } 50 | 51 | /** 52 | * Reads the next item from the target, updating internal flags in the process 53 | * @return the next int read from the target stream 54 | * @throws IOException upon error 55 | */ 56 | private int readWithUpdate() throws IOException { 57 | final int target = this.target.read(); 58 | eofSeen = target == -1; 59 | if ( eofSeen ) { 60 | return target; 61 | } 62 | slashNSeen = target == '\n'; 63 | slashRSeen = target == '\r'; 64 | return target; 65 | } 66 | 67 | /** 68 | * {@inheritDoc} 69 | */ 70 | @Override 71 | public int read() throws IOException { 72 | final boolean previousWasSlashR = slashRSeen; 73 | if ( eofSeen ) { 74 | return eofGame(previousWasSlashR); 75 | } 76 | else { 77 | final int target = readWithUpdate(); 78 | if ( eofSeen ) { 79 | return eofGame(previousWasSlashR); 80 | } 81 | if (slashRSeen) 82 | { 83 | return '\n'; 84 | } 85 | 86 | if ( previousWasSlashR && slashNSeen){ 87 | return read(); 88 | } 89 | 90 | return target; 91 | } 92 | } 93 | 94 | /** 95 | * Handles the eof-handling at the end of the stream 96 | * @param previousWasSlashR Indicates if the last seen was a \r 97 | * @return The next char to output to the stream 98 | */ 99 | private int eofGame(final boolean previousWasSlashR) { 100 | if ( previousWasSlashR || !ensureLineFeedAtEndOfFile ) { 101 | return -1; 102 | } 103 | if ( !slashNSeen ) { 104 | slashNSeen = true; 105 | return '\n'; 106 | } else { 107 | return -1; 108 | } 109 | } 110 | 111 | /** 112 | * Closes the stream. Also closes the underlying stream. 113 | * @throws IOException upon error 114 | */ 115 | @Override 116 | public void close() throws IOException { 117 | super.close(); 118 | target.close(); 119 | } 120 | 121 | /** 122 | * {@inheritDoc} 123 | */ 124 | @Override 125 | public synchronized void mark( final int readlimit ) { 126 | throw new UnsupportedOperationException( "Mark notsupported" ); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/WindowsLineEndingInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | import java.io.IOException; 20 | import java.io.InputStream; 21 | 22 | /** 23 | * A filtering input stream that ensures the content will have windows line endings, CRLF. 24 | * 25 | * @since 2.5 26 | */ 27 | public class WindowsLineEndingInputStream extends InputStream { 28 | 29 | private boolean slashRSeen = false; 30 | 31 | private boolean slashNSeen = false; 32 | 33 | private boolean injectSlashN = false; 34 | 35 | private boolean eofSeen = false; 36 | 37 | private final InputStream target; 38 | 39 | private final boolean ensureLineFeedAtEndOfFile; 40 | 41 | /** 42 | * Create an input stream that filters another stream 43 | * 44 | * @param in The input stream to wrap 45 | * @param ensureLineFeedAtEndOfFile true to ensure that the file ends with CRLF 46 | */ 47 | public WindowsLineEndingInputStream( final InputStream in, final boolean ensureLineFeedAtEndOfFile ) { 48 | this.target = in; 49 | this.ensureLineFeedAtEndOfFile = ensureLineFeedAtEndOfFile; 50 | } 51 | 52 | /** 53 | * Reads the next item from the target, updating internal flags in the process 54 | * @return the next int read from the target stream 55 | * @throws IOException upon error 56 | */ 57 | private int readWithUpdate() throws IOException { 58 | final int target = this.target.read(); 59 | eofSeen = target == -1; 60 | if ( eofSeen ) { 61 | return target; 62 | } 63 | slashRSeen = target == '\r'; 64 | slashNSeen = target == '\n'; 65 | return target; 66 | } 67 | 68 | /** 69 | * {@inheritDoc} 70 | */ 71 | @Override 72 | public int read() throws IOException { 73 | if ( eofSeen ) { 74 | return eofGame(); 75 | } else if ( injectSlashN ) { 76 | injectSlashN = false; 77 | return '\n'; 78 | } else { 79 | final boolean prevWasSlashR = slashRSeen; 80 | final int target = readWithUpdate(); 81 | if ( eofSeen ) { 82 | return eofGame(); 83 | } 84 | if ( target == '\n' ) { 85 | if ( !prevWasSlashR ) 86 | { 87 | injectSlashN = true; 88 | return '\r'; 89 | } 90 | } 91 | return target; 92 | } 93 | } 94 | 95 | /** 96 | * Handles the eof-handling at the end of the stream 97 | * @return The next char to output to the stream 98 | */ 99 | 100 | private int eofGame() { 101 | if ( !ensureLineFeedAtEndOfFile ) { 102 | return -1; 103 | } 104 | if ( !slashNSeen && !slashRSeen ) { 105 | slashRSeen = true; 106 | return '\r'; 107 | } 108 | if ( !slashNSeen ) { 109 | slashRSeen = false; 110 | slashNSeen = true; 111 | return '\n'; 112 | } else { 113 | return -1; 114 | } 115 | } 116 | 117 | /** 118 | * Closes the stream. Also closes the underlying stream. 119 | * @throws IOException upon error 120 | */ 121 | @Override 122 | public void close() throws IOException { 123 | super.close(); 124 | target.close(); 125 | } 126 | 127 | /** 128 | * {@inheritDoc} 129 | */ 130 | @Override 131 | public synchronized void mark( final int readlimit ) { 132 | throw new UnsupportedOperationException( "Mark not supported" ); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/XmlStreamReaderException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.input; 18 | 19 | import java.io.IOException; 20 | 21 | /** 22 | * The XmlStreamReaderException is thrown by the XmlStreamReader constructors if 23 | * the charset encoding can not be determined according to the XML 1.0 24 | * specification and RFC 3023. 25 | *

26 | * The exception returns the unconsumed InputStream to allow the application to 27 | * do an alternate processing with the stream. Note that the original 28 | * InputStream given to the XmlStreamReader cannot be used as that one has been 29 | * already read. 30 | * 31 | * @since 2.0 32 | */ 33 | public class XmlStreamReaderException extends IOException { 34 | 35 | private static final long serialVersionUID = 1L; 36 | 37 | private final String bomEncoding; 38 | 39 | private final String xmlGuessEncoding; 40 | 41 | private final String xmlEncoding; 42 | 43 | private final String contentTypeMime; 44 | 45 | private final String contentTypeEncoding; 46 | 47 | /** 48 | * Creates an exception instance if the charset encoding could not be 49 | * determined. 50 | *

51 | * Instances of this exception are thrown by the XmlStreamReader. 52 | * 53 | * @param msg message describing the reason for the exception. 54 | * @param bomEnc BOM encoding. 55 | * @param xmlGuessEnc XML guess encoding. 56 | * @param xmlEnc XML prolog encoding. 57 | */ 58 | public XmlStreamReaderException(final String msg, final String bomEnc, 59 | final String xmlGuessEnc, final String xmlEnc) { 60 | this(msg, null, null, bomEnc, xmlGuessEnc, xmlEnc); 61 | } 62 | 63 | /** 64 | * Creates an exception instance if the charset encoding could not be 65 | * determined. 66 | *

67 | * Instances of this exception are thrown by the XmlStreamReader. 68 | * 69 | * @param msg message describing the reason for the exception. 70 | * @param ctMime MIME type in the content-type. 71 | * @param ctEnc encoding in the content-type. 72 | * @param bomEnc BOM encoding. 73 | * @param xmlGuessEnc XML guess encoding. 74 | * @param xmlEnc XML prolog encoding. 75 | */ 76 | public XmlStreamReaderException(final String msg, final String ctMime, final String ctEnc, 77 | final String bomEnc, final String xmlGuessEnc, final String xmlEnc) { 78 | super(msg); 79 | contentTypeMime = ctMime; 80 | contentTypeEncoding = ctEnc; 81 | bomEncoding = bomEnc; 82 | xmlGuessEncoding = xmlGuessEnc; 83 | xmlEncoding = xmlEnc; 84 | } 85 | 86 | /** 87 | * Returns the BOM encoding found in the InputStream. 88 | * 89 | * @return the BOM encoding, null if none. 90 | */ 91 | public String getBomEncoding() { 92 | return bomEncoding; 93 | } 94 | 95 | /** 96 | * Returns the encoding guess based on the first bytes of the InputStream. 97 | * 98 | * @return the encoding guess, null if it couldn't be guessed. 99 | */ 100 | public String getXmlGuessEncoding() { 101 | return xmlGuessEncoding; 102 | } 103 | 104 | /** 105 | * Returns the encoding found in the XML prolog of the InputStream. 106 | * 107 | * @return the encoding of the XML prolog, null if none. 108 | */ 109 | public String getXmlEncoding() { 110 | return xmlEncoding; 111 | } 112 | 113 | /** 114 | * Returns the MIME type in the content-type used to attempt determining the 115 | * encoding. 116 | * 117 | * @return the MIME type in the content-type, null if there was not 118 | * content-type or the encoding detection did not involve HTTP. 119 | */ 120 | public String getContentTypeMime() { 121 | return contentTypeMime; 122 | } 123 | 124 | /** 125 | * Returns the encoding in the content-type used to attempt determining the 126 | * encoding. 127 | * 128 | * @return the encoding in the content-type, null if there was not 129 | * content-type, no encoding in it or the encoding detection did not 130 | * involve HTTP. 131 | */ 132 | public String getContentTypeEncoding() { 133 | return contentTypeEncoding; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/input/package.html: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 |

21 | This package provides implementations of input classes, such as 22 | InputStream and Reader. 23 |

24 | 25 | 26 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/monitor/FileAlterationListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.monitor; 18 | import java.io.File; 19 | 20 | /** 21 | * A listener that receives events of file system modifications. 22 | *

23 | * Register {@link FileAlterationListener}s with a {@link FileAlterationObserver}. 24 | * 25 | * @see FileAlterationObserver 26 | * @version $Id$ 27 | * @since 2.0 28 | */ 29 | public interface FileAlterationListener { 30 | 31 | /** 32 | * File system observer started checking event. 33 | * 34 | * @param observer The file system observer 35 | */ 36 | void onStart(final FileAlterationObserver observer); 37 | 38 | /** 39 | * Directory created Event. 40 | * 41 | * @param directory The directory created 42 | */ 43 | void onDirectoryCreate(final File directory); 44 | 45 | /** 46 | * Directory changed Event. 47 | * 48 | * @param directory The directory changed 49 | */ 50 | void onDirectoryChange(final File directory); 51 | 52 | /** 53 | * Directory deleted Event. 54 | * 55 | * @param directory The directory deleted 56 | */ 57 | void onDirectoryDelete(final File directory); 58 | 59 | /** 60 | * File created Event. 61 | * 62 | * @param file The file created 63 | */ 64 | void onFileCreate(final File file); 65 | 66 | /** 67 | * File changed Event. 68 | * 69 | * @param file The file changed 70 | */ 71 | void onFileChange(final File file); 72 | 73 | /** 74 | * File deleted Event. 75 | * 76 | * @param file The file deleted 77 | */ 78 | void onFileDelete(final File file); 79 | 80 | /** 81 | * File system observer finished checking event. 82 | * 83 | * @param observer The file system observer 84 | */ 85 | void onStop(final FileAlterationObserver observer); 86 | } 87 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.monitor; 18 | 19 | import java.io.File; 20 | 21 | /** 22 | * Convenience {@link FileAlterationListener} implementation that does nothing. 23 | * 24 | * @see FileAlterationObserver 25 | * @version $Id$ 26 | * @since 2.0 27 | */ 28 | public class FileAlterationListenerAdaptor implements FileAlterationListener { 29 | 30 | /** 31 | * File system observer started checking event. 32 | * 33 | * @param observer The file system observer (ignored) 34 | */ 35 | @Override 36 | public void onStart(final FileAlterationObserver observer) { 37 | } 38 | 39 | /** 40 | * Directory created Event. 41 | * 42 | * @param directory The directory created (ignored) 43 | */ 44 | @Override 45 | public void onDirectoryCreate(final File directory) { 46 | } 47 | 48 | /** 49 | * Directory changed Event. 50 | * 51 | * @param directory The directory changed (ignored) 52 | */ 53 | @Override 54 | public void onDirectoryChange(final File directory) { 55 | } 56 | 57 | /** 58 | * Directory deleted Event. 59 | * 60 | * @param directory The directory deleted (ignored) 61 | */ 62 | @Override 63 | public void onDirectoryDelete(final File directory) { 64 | } 65 | 66 | /** 67 | * File created Event. 68 | * 69 | * @param file The file created (ignored) 70 | */ 71 | @Override 72 | public void onFileCreate(final File file) { 73 | } 74 | 75 | /** 76 | * File changed Event. 77 | * 78 | * @param file The file changed (ignored) 79 | */ 80 | @Override 81 | public void onFileChange(final File file) { 82 | } 83 | 84 | /** 85 | * File deleted Event. 86 | * 87 | * @param file The file deleted (ignored) 88 | */ 89 | @Override 90 | public void onFileDelete(final File file) { 91 | } 92 | 93 | /** 94 | * File system observer finished checking event. 95 | * 96 | * @param observer The file system observer (ignored) 97 | */ 98 | @Override 99 | public void onStop(final FileAlterationObserver observer) { 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/monitor/package.html: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 |

21 | This package provides a component for monitoring file system events 22 | (directory and file create, update and delete events). 23 |

24 | 25 | 26 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/AppendableOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.output; 18 | 19 | import java.io.IOException; 20 | import java.io.OutputStream; 21 | 22 | /** 23 | * OutputStream implementation that writes the data to an {@link Appendable} 24 | * Object. 25 | *

26 | * For example, can be used with any {@link java.io.Writer} or a {@link java.lang.StringBuilder} 27 | * or {@link java.lang.StringBuffer}. 28 | * 29 | * @since 2.5 30 | * @see java.lang.Appendable 31 | * @version $Id$ 32 | */ 33 | public class AppendableOutputStream extends OutputStream { 34 | 35 | private final T appendable; 36 | 37 | /** 38 | * Construct a new instance with the specified appendable. 39 | * 40 | * @param appendable the appendable to write to 41 | */ 42 | public AppendableOutputStream(final T appendable) { 43 | this.appendable = appendable; 44 | } 45 | 46 | /** 47 | * Write a character to the underlying appendable. 48 | * 49 | * @param b the character to write 50 | * @throws IOException upon error 51 | */ 52 | @Override 53 | public void write(final int b) throws IOException { 54 | appendable.append((char)b); 55 | } 56 | 57 | /** 58 | * Return the target appendable. 59 | * 60 | * @return the target appendable 61 | */ 62 | public T getAppendable() { 63 | return appendable; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/BrokenOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.output; 18 | 19 | import java.io.IOException; 20 | import java.io.OutputStream; 21 | 22 | /** 23 | * Broken output stream. This stream always throws an {@link IOException} from 24 | * all {@link OutputStream} methods. 25 | *

26 | * This class is mostly useful for testing error handling in code that uses an 27 | * output stream. 28 | * 29 | * @since 2.0 30 | */ 31 | public class BrokenOutputStream extends OutputStream { 32 | 33 | /** 34 | * The exception that is thrown by all methods of this class. 35 | */ 36 | private final IOException exception; 37 | 38 | /** 39 | * Creates a new stream that always throws the given exception. 40 | * 41 | * @param exception the exception to be thrown 42 | */ 43 | public BrokenOutputStream(final IOException exception) { 44 | this.exception = exception; 45 | } 46 | 47 | /** 48 | * Creates a new stream that always throws an {@link IOException} 49 | */ 50 | public BrokenOutputStream() { 51 | this(new IOException("Broken output stream")); 52 | } 53 | 54 | /** 55 | * Throws the configured exception. 56 | * 57 | * @param b ignored 58 | * @throws IOException always thrown 59 | */ 60 | @Override 61 | public void write(final int b) throws IOException { 62 | throw exception; 63 | } 64 | 65 | /** 66 | * Throws the configured exception. 67 | * 68 | * @throws IOException always thrown 69 | */ 70 | @Override 71 | public void flush() throws IOException { 72 | throw exception; 73 | } 74 | 75 | /** 76 | * Throws the configured exception. 77 | * 78 | * @throws IOException always thrown 79 | */ 80 | @Override 81 | public void close() throws IOException { 82 | throw exception; 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/ChunkedOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.output; 18 | 19 | import java.io.FilterOutputStream; 20 | import java.io.IOException; 21 | import java.io.OutputStream; 22 | 23 | /** 24 | * OutputStream which breaks larger output blocks into chunks. 25 | * Native code may need to copy the input array; if the write buffer 26 | * is very large this can cause OOME. 27 | * 28 | * @since 2.5 29 | */ 30 | public class ChunkedOutputStream extends FilterOutputStream { 31 | 32 | /** 33 | * The default chunk size to use, i.e. {@value} bytes. 34 | */ 35 | private static final int DEFAULT_CHUNK_SIZE = 1024 * 4; 36 | 37 | /** 38 | * The maximum chunk size to us when writing data arrays 39 | */ 40 | private final int chunkSize; 41 | 42 | /** 43 | * Creates a new stream that uses the specified chunk size. 44 | * 45 | * @param stream the stream to wrap 46 | * @param chunkSize the chunk size to use; must be a positive number. 47 | * @throws IllegalArgumentException if the chunk size is <= 0 48 | */ 49 | public ChunkedOutputStream(final OutputStream stream, final int chunkSize) { 50 | super(stream); 51 | if (chunkSize <= 0) { 52 | throw new IllegalArgumentException(); 53 | } 54 | this.chunkSize = chunkSize; 55 | } 56 | 57 | /** 58 | * Creates a new stream that uses a chunk size of {@link #DEFAULT_CHUNK_SIZE}. 59 | * 60 | * @param stream the stream to wrap 61 | */ 62 | public ChunkedOutputStream(final OutputStream stream) { 63 | this(stream, DEFAULT_CHUNK_SIZE); 64 | } 65 | 66 | /** 67 | * Writes the data buffer in chunks to the underlying stream 68 | * 69 | * @param data the data to write 70 | * @param srcOffset the offset 71 | * @param length the length of data to write 72 | * 73 | * @throws IOException if an I/O error occurs. 74 | */ 75 | @Override 76 | public void write(final byte[] data, final int srcOffset, final int length) throws IOException { 77 | int bytes = length; 78 | int dstOffset = srcOffset; 79 | while(bytes > 0) { 80 | final int chunk = Math.min(bytes, chunkSize); 81 | out.write(data, dstOffset, chunk); 82 | bytes -= chunk; 83 | dstOffset += chunk; 84 | } 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/ChunkedWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.output; 18 | 19 | import java.io.FilterWriter; 20 | import java.io.IOException; 21 | import java.io.Writer; 22 | 23 | /** 24 | * Writer which breaks larger output blocks into chunks. 25 | * Native code may need to copy the input array; if the write buffer 26 | * is very large this can cause OOME. 27 | * 28 | * @since 2.5 29 | */ 30 | public class ChunkedWriter extends FilterWriter { 31 | 32 | /** 33 | * The default chunk size to use, i.e. {@value} bytes. 34 | */ 35 | private static final int DEFAULT_CHUNK_SIZE = 1024 * 4; 36 | 37 | /** 38 | * The maximum chunk size to us when writing data arrays 39 | */ 40 | private final int chunkSize; 41 | 42 | /** 43 | * Creates a new writer that uses the specified chunk size. 44 | * 45 | * @param writer the writer to wrap 46 | * @param chunkSize the chunk size to use; must be a positive number. 47 | * @throws IllegalArgumentException if the chunk size is <= 0 48 | */ 49 | public ChunkedWriter(final Writer writer, final int chunkSize) { 50 | super(writer); 51 | if (chunkSize <= 0) { 52 | throw new IllegalArgumentException(); 53 | } 54 | this.chunkSize = chunkSize; 55 | } 56 | 57 | /** 58 | * Creates a new writer that uses a chunk size of {@link #DEFAULT_CHUNK_SIZE} 59 | * @param writer the writer to wrap 60 | */ 61 | public ChunkedWriter(final Writer writer) { 62 | this(writer, DEFAULT_CHUNK_SIZE); 63 | } 64 | 65 | /** 66 | * writes the data buffer in chunks to the underlying writer 67 | * @param data The data 68 | * @param srcOffset the offset 69 | * @param length the number of bytes to write 70 | * 71 | * @throws IOException upon error 72 | */ 73 | @Override 74 | public void write(final char[] data, final int srcOffset, final int length) throws IOException { 75 | int bytes = length; 76 | int dstOffset = srcOffset; 77 | while(bytes > 0) { 78 | final int chunk = Math.min(bytes, chunkSize); 79 | out.write(data, dstOffset, chunk); 80 | bytes -= chunk; 81 | dstOffset += chunk; 82 | } 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/CloseShieldOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.output; 18 | 19 | import java.io.OutputStream; 20 | 21 | /** 22 | * Proxy stream that prevents the underlying output stream from being closed. 23 | *

24 | * This class is typically used in cases where an output stream needs to be 25 | * passed to a component that wants to explicitly close the stream even if 26 | * other components would still use the stream for output. 27 | *

28 | * @version $Id$ 29 | * @since 1.4 30 | */ 31 | public class CloseShieldOutputStream extends ProxyOutputStream { 32 | 33 | /** 34 | * Creates a proxy that shields the given output stream from being 35 | * closed. 36 | * 37 | * @param out underlying output stream 38 | */ 39 | public CloseShieldOutputStream(final OutputStream out) { 40 | super(out); 41 | } 42 | 43 | /** 44 | * Replaces the underlying output stream with a {@link ClosedOutputStream} 45 | * sentinel. The original output stream will remain open, but this proxy 46 | * will appear closed. 47 | */ 48 | @Override 49 | public void close() { 50 | out = new ClosedOutputStream(); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/ClosedOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.output; 18 | 19 | import java.io.IOException; 20 | import java.io.OutputStream; 21 | 22 | /** 23 | * Closed output stream. This stream throws an exception on all attempts to 24 | * write something to the stream. 25 | *

26 | * Typically uses of this class include testing for corner cases in methods 27 | * that accept an output stream and acting as a sentinel value instead of 28 | * a {@code null} output stream. 29 | * 30 | * @since 1.4 31 | */ 32 | public class ClosedOutputStream extends OutputStream { 33 | 34 | /** 35 | * A singleton. 36 | */ 37 | public static final ClosedOutputStream CLOSED_OUTPUT_STREAM = new ClosedOutputStream(); 38 | 39 | /** 40 | * Throws an {@link IOException} to indicate that the stream is closed. 41 | * 42 | * @param b ignored 43 | * @throws IOException always thrown 44 | */ 45 | @Override 46 | public void write(final int b) throws IOException { 47 | throw new IOException("write(" + b + ") failed: stream is closed"); 48 | } 49 | 50 | /** 51 | * Throws an {@link IOException} to indicate that the stream is closed. 52 | * 53 | * @throws IOException always thrown 54 | */ 55 | @Override 56 | public void flush() throws IOException { 57 | throw new IOException("flush() failed: stream is closed"); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/CountingOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.output; 18 | 19 | import java.io.OutputStream; 20 | 21 | /** 22 | * A decorating output stream that counts the number of bytes that have passed 23 | * through the stream so far. 24 | *

25 | * A typical use case would be during debugging, to ensure that data is being 26 | * written as expected. 27 | * 28 | */ 29 | public class CountingOutputStream extends ProxyOutputStream { 30 | 31 | /** The count of bytes that have passed. */ 32 | private long count = 0; 33 | 34 | /** 35 | * Constructs a new CountingOutputStream. 36 | * 37 | * @param out the OutputStream to write to 38 | */ 39 | public CountingOutputStream( final OutputStream out ) { 40 | super(out); 41 | } 42 | 43 | //----------------------------------------------------------------------- 44 | 45 | /** 46 | * Updates the count with the number of bytes that are being written. 47 | * 48 | * @param n number of bytes to be written to the stream 49 | * @since 2.0 50 | */ 51 | @Override 52 | protected synchronized void beforeWrite(final int n) { 53 | count += n; 54 | } 55 | 56 | //----------------------------------------------------------------------- 57 | /** 58 | * The number of bytes that have passed through this stream. 59 | *

60 | * NOTE: From v1.3 this method throws an ArithmeticException if the 61 | * count is greater than can be expressed by an int. 62 | * See {@link #getByteCount()} for a method using a long. 63 | * 64 | * @return the number of bytes accumulated 65 | * @throws ArithmeticException if the byte count is too large 66 | */ 67 | public int getCount() { 68 | final long result = getByteCount(); 69 | if (result > Integer.MAX_VALUE) { 70 | throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int"); 71 | } 72 | return (int) result; 73 | } 74 | 75 | /** 76 | * Set the byte count back to 0. 77 | *

78 | * NOTE: From v1.3 this method throws an ArithmeticException if the 79 | * count is greater than can be expressed by an int. 80 | * See {@link #resetByteCount()} for a method using a long. 81 | * 82 | * @return the count previous to resetting 83 | * @throws ArithmeticException if the byte count is too large 84 | */ 85 | public int resetCount() { 86 | final long result = resetByteCount(); 87 | if (result > Integer.MAX_VALUE) { 88 | throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int"); 89 | } 90 | return (int) result; 91 | } 92 | 93 | /** 94 | * The number of bytes that have passed through this stream. 95 | *

96 | * NOTE: This method is an alternative for getCount(). 97 | * It was added because that method returns an integer which will 98 | * result in incorrect count for files over 2GB. 99 | * 100 | * @return the number of bytes accumulated 101 | * @since 1.3 102 | */ 103 | public synchronized long getByteCount() { 104 | return this.count; 105 | } 106 | 107 | /** 108 | * Set the byte count back to 0. 109 | *

110 | * NOTE: This method is an alternative for resetCount(). 111 | * It was added because that method returns an integer which will 112 | * result in incorrect count for files over 2GB. 113 | * 114 | * @return the count previous to resetting 115 | * @since 1.3 116 | */ 117 | public synchronized long resetByteCount() { 118 | final long tmp = this.count; 119 | this.count = 0; 120 | return tmp; 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/DemuxOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.output; 18 | 19 | import java.io.IOException; 20 | import java.io.OutputStream; 21 | 22 | /** 23 | * Forwards data to a stream that has been associated with this thread. 24 | * 25 | */ 26 | public class DemuxOutputStream extends OutputStream { 27 | private final InheritableThreadLocal outputStreamThreadLocal = new InheritableThreadLocal<>(); 28 | 29 | /** 30 | * Binds the specified stream to the current thread. 31 | * 32 | * @param output 33 | * the stream to bind 34 | * @return the OutputStream that was previously active 35 | */ 36 | public OutputStream bindStream(final OutputStream output) { 37 | final OutputStream stream = outputStreamThreadLocal.get(); 38 | outputStreamThreadLocal.set(output); 39 | return stream; 40 | } 41 | 42 | /** 43 | * Closes stream associated with current thread. 44 | * 45 | * @throws IOException 46 | * if an error occurs 47 | */ 48 | @Override 49 | public void close() throws IOException { 50 | final OutputStream output = outputStreamThreadLocal.get(); 51 | if (null != output) { 52 | output.close(); 53 | } 54 | } 55 | 56 | /** 57 | * Flushes stream associated with current thread. 58 | * 59 | * @throws IOException 60 | * if an error occurs 61 | */ 62 | @Override 63 | public void flush() throws IOException { 64 | @SuppressWarnings("resource") 65 | final OutputStream output = outputStreamThreadLocal.get(); 66 | if (null != output) { 67 | output.flush(); 68 | } 69 | } 70 | 71 | /** 72 | * Writes byte to stream associated with current thread. 73 | * 74 | * @param ch 75 | * the byte to write to stream 76 | * @throws IOException 77 | * if an error occurs 78 | */ 79 | @Override 80 | public void write(final int ch) throws IOException { 81 | @SuppressWarnings("resource") 82 | final OutputStream output = outputStreamThreadLocal.get(); 83 | if (null != output) { 84 | output.write(ch); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/NullOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.output; 18 | 19 | import java.io.IOException; 20 | import java.io.OutputStream; 21 | 22 | /** 23 | * This OutputStream writes all data to the famous /dev/null. 24 | *

25 | * This output stream has no destination (file/socket etc.) and all 26 | * bytes written to it are ignored and lost. 27 | *

28 | * @version $Id$ 29 | */ 30 | public class NullOutputStream extends OutputStream { 31 | 32 | /** 33 | * A singleton. 34 | */ 35 | public static final NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream(); 36 | 37 | /** 38 | * Does nothing - output to /dev/null. 39 | * @param b The bytes to write 40 | * @param off The start offset 41 | * @param len The number of bytes to write 42 | */ 43 | @Override 44 | public void write(final byte[] b, final int off, final int len) { 45 | //to /dev/null 46 | } 47 | 48 | /** 49 | * Does nothing - output to /dev/null. 50 | * @param b The byte to write 51 | */ 52 | @Override 53 | public void write(final int b) { 54 | //to /dev/null 55 | } 56 | 57 | /** 58 | * Does nothing - output to /dev/null. 59 | * @param b The bytes to write 60 | * @throws IOException never 61 | */ 62 | @Override 63 | public void write(final byte[] b) throws IOException { 64 | //to /dev/null 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/NullWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.output; 18 | 19 | import java.io.Writer; 20 | 21 | /** 22 | * This {@link Writer} writes all data to the famous /dev/null. 23 | *

24 | * This Writer has no destination (file/socket etc.) and all 25 | * characters written to it are ignored and lost. 26 | * 27 | */ 28 | public class NullWriter extends Writer { 29 | 30 | /** 31 | * A singleton. 32 | */ 33 | public static final NullWriter NULL_WRITER = new NullWriter(); 34 | 35 | /** 36 | * Constructs a new NullWriter. 37 | */ 38 | public NullWriter() { 39 | } 40 | 41 | /** 42 | * Does nothing - output to /dev/null. 43 | * @param c The character to write 44 | * @return this writer 45 | * @since 2.0 46 | */ 47 | @Override 48 | public Writer append(final char c) { 49 | //to /dev/null 50 | return this; 51 | } 52 | 53 | /** 54 | * Does nothing - output to /dev/null. 55 | * @param csq The character sequence to write 56 | * @param start The index of the first character to write 57 | * @param end The index of the first character to write (exclusive) 58 | * @return this writer 59 | * @since 2.0 60 | */ 61 | @Override 62 | public Writer append(final CharSequence csq, final int start, final int end) { 63 | //to /dev/null 64 | return this; 65 | } 66 | 67 | /** 68 | * Does nothing - output to /dev/null. 69 | * @param csq The character sequence to write 70 | * @return this writer 71 | * @since 2.0 72 | */ 73 | @Override 74 | public Writer append(final CharSequence csq) { 75 | //to /dev/null 76 | return this; 77 | } 78 | 79 | /** 80 | * Does nothing - output to /dev/null. 81 | * @param idx The character to write 82 | */ 83 | @Override 84 | public void write(final int idx) { 85 | //to /dev/null 86 | } 87 | 88 | /** 89 | * Does nothing - output to /dev/null. 90 | * @param chr The characters to write 91 | */ 92 | @Override 93 | public void write(final char[] chr) { 94 | //to /dev/null 95 | } 96 | 97 | /** 98 | * Does nothing - output to /dev/null. 99 | * @param chr The characters to write 100 | * @param st The start offset 101 | * @param end The number of characters to write 102 | */ 103 | @Override 104 | public void write(final char[] chr, final int st, final int end) { 105 | //to /dev/null 106 | } 107 | 108 | /** 109 | * Does nothing - output to /dev/null. 110 | * @param str The string to write 111 | */ 112 | @Override 113 | public void write(final String str) { 114 | //to /dev/null 115 | } 116 | 117 | /** 118 | * Does nothing - output to /dev/null. 119 | * @param str The string to write 120 | * @param st The start offset 121 | * @param end The number of characters to write 122 | */ 123 | @Override 124 | public void write(final String str, final int st, final int end) { 125 | //to /dev/null 126 | } 127 | 128 | /** @see java.io.Writer#flush() */ 129 | @Override 130 | public void flush() { 131 | //to /dev/null 132 | } 133 | 134 | /** @see java.io.Writer#close() */ 135 | @Override 136 | public void close() { 137 | //to /dev/null 138 | } 139 | 140 | } 141 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/TaggedOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.output; 18 | 19 | import java.io.IOException; 20 | import java.io.OutputStream; 21 | import java.io.Serializable; 22 | import java.util.UUID; 23 | 24 | import org.apache.commons.io.TaggedIOException; 25 | 26 | /** 27 | * An output stream decorator that tags potential exceptions so that the 28 | * stream that caused the exception can easily be identified. This is 29 | * done by using the {@link TaggedIOException} class to wrap all thrown 30 | * {@link IOException}s. See below for an example of using this class. 31 | *

 32 |  * TaggedOutputStream stream = new TaggedOutputStream(...);
 33 |  * try {
 34 |  *     // Processing that may throw an IOException either from this stream
 35 |  *     // or from some other IO activity like temporary files, etc.
 36 |  *     writeToStream(stream);
 37 |  * } catch (IOException e) {
 38 |  *     if (stream.isCauseOf(e)) {
 39 |  *         // The exception was caused by this stream.
 40 |  *         // Use e.getCause() to get the original exception.
 41 |  *     } else {
 42 |  *         // The exception was caused by something else.
 43 |  *     }
 44 |  * }
 45 |  * 
46 | *

47 | * Alternatively, the {@link #throwIfCauseOf(Exception)} method can be 48 | * used to let higher levels of code handle the exception caused by this 49 | * stream while other processing errors are being taken care of at this 50 | * lower level. 51 | *

 52 |  * TaggedOutputStream stream = new TaggedOutputStream(...);
 53 |  * try {
 54 |  *     writeToStream(stream);
 55 |  * } catch (IOException e) {
 56 |  *     stream.throwIfCauseOf(e);
 57 |  *     // ... or process the exception that was caused by something else
 58 |  * }
 59 |  * 
60 | * 61 | * @see TaggedIOException 62 | * @since 2.0 63 | */ 64 | public class TaggedOutputStream extends ProxyOutputStream { 65 | 66 | /** 67 | * The unique tag associated with exceptions from stream. 68 | */ 69 | private final Serializable tag = UUID.randomUUID(); 70 | 71 | /** 72 | * Creates a tagging decorator for the given output stream. 73 | * 74 | * @param proxy output stream to be decorated 75 | */ 76 | public TaggedOutputStream(final OutputStream proxy) { 77 | super(proxy); 78 | } 79 | 80 | /** 81 | * Tests if the given exception was caused by this stream. 82 | * 83 | * @param exception an exception 84 | * @return {@code true} if the exception was thrown by this stream, 85 | * {@code false} otherwise 86 | */ 87 | public boolean isCauseOf(final Exception exception) { 88 | return TaggedIOException.isTaggedWith(exception, tag); 89 | } 90 | 91 | /** 92 | * Re-throws the original exception thrown by this stream. This method 93 | * first checks whether the given exception is a {@link TaggedIOException} 94 | * wrapper created by this decorator, and then unwraps and throws the 95 | * original wrapped exception. Returns normally if the exception was 96 | * not thrown by this stream. 97 | * 98 | * @param exception an exception 99 | * @throws IOException original exception, if any, thrown by this stream 100 | */ 101 | public void throwIfCauseOf(final Exception exception) throws IOException { 102 | TaggedIOException.throwCauseIfTaggedWith(exception, tag); 103 | } 104 | 105 | /** 106 | * Tags any IOExceptions thrown, wrapping and re-throwing. 107 | * 108 | * @param e The IOException thrown 109 | * @throws IOException if an I/O error occurs 110 | */ 111 | @Override 112 | protected void handleIOException(final IOException e) throws IOException { 113 | throw new TaggedIOException(e, tag); 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/TeeOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package org.apache.commons.io.output; 18 | 19 | import java.io.IOException; 20 | import java.io.OutputStream; 21 | 22 | /** 23 | * Classic splitter of OutputStream. Named after the unix 'tee' 24 | * command. It allows a stream to be branched off so there 25 | * are now two streams. 26 | * 27 | */ 28 | public class TeeOutputStream extends ProxyOutputStream { 29 | 30 | /** the second OutputStream to write to */ 31 | protected OutputStream branch; //TODO consider making this private 32 | 33 | /** 34 | * Constructs a TeeOutputStream. 35 | * @param out the main OutputStream 36 | * @param branch the second OutputStream 37 | */ 38 | public TeeOutputStream(final OutputStream out, final OutputStream branch) { 39 | super(out); 40 | this.branch = branch; 41 | } 42 | 43 | /** 44 | * Write the bytes to both streams. 45 | * @param b the bytes to write 46 | * @throws IOException if an I/O error occurs 47 | */ 48 | @Override 49 | public synchronized void write(final byte[] b) throws IOException { 50 | super.write(b); 51 | this.branch.write(b); 52 | } 53 | 54 | /** 55 | * Write the specified bytes to both streams. 56 | * @param b the bytes to write 57 | * @param off The start offset 58 | * @param len The number of bytes to write 59 | * @throws IOException if an I/O error occurs 60 | */ 61 | @Override 62 | public synchronized void write(final byte[] b, final int off, final int len) throws IOException { 63 | super.write(b, off, len); 64 | this.branch.write(b, off, len); 65 | } 66 | 67 | /** 68 | * Write a byte to both streams. 69 | * @param b the byte to write 70 | * @throws IOException if an I/O error occurs 71 | */ 72 | @Override 73 | public synchronized void write(final int b) throws IOException { 74 | super.write(b); 75 | this.branch.write(b); 76 | } 77 | 78 | /** 79 | * Flushes both streams. 80 | * @throws IOException if an I/O error occurs 81 | */ 82 | @Override 83 | public void flush() throws IOException { 84 | super.flush(); 85 | this.branch.flush(); 86 | } 87 | 88 | /** 89 | * Closes both output streams. 90 | * 91 | * If closing the main output stream throws an exception, attempt to close the branch output stream. 92 | * 93 | * If closing the main and branch output streams both throw exceptions, which exceptions is thrown by this method is 94 | * currently unspecified and subject to change. 95 | * 96 | * @throws IOException 97 | * if an I/O error occurs 98 | */ 99 | @Override 100 | public void close() throws IOException { 101 | try { 102 | super.close(); 103 | } finally { 104 | this.branch.close(); 105 | } 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/output/package.html: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 |

21 | This package provides implementations of output classes, such as 22 | OutputStream and Writer. 23 |

24 | 25 | 26 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/overview.html: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 |

21 | The commons-io component contains utility classes, 22 | filters, streams, readers and writers. 23 |

24 |

25 | These classes aim to add to the standard JDK IO classes. 26 | The utilities provide convenience wrappers around the JDK, simplifying 27 | various operations into pre-tested units of code. 28 | The filters and streams provide useful implementations that perhaps should 29 | be in the JDK itself. 30 |

31 | 32 | 33 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/package.html: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 |

21 | This package defines utility classes for working with streams, readers, 22 | writers and files. The most commonly used classes are described here: 23 |

24 |

25 | IOUtils is the most frequently used class. 26 | It provides operations to read, write, copy and close streams. 27 |

28 |

29 | FileUtils provides operations based around the JDK File class. 30 | These include reading, writing, copying, comparing and deleting. 31 |

32 |

33 | FilenameUtils provides utilities based on filenames. 34 | This utility class manipulates filenames without using File objects. 35 | It aims to simplify the transition between Windows and Unix. 36 | Before using this class however, you should consider whether you should 37 | be using File objects. 38 |

39 |

40 | FileSystemUtils allows access to the filing system in ways the JDK 41 | does not support. At present this allows you to get the free space on a drive. 42 |

43 |

44 | EndianUtils swaps data between Big-Endian and Little-Endian formats. 45 |

46 | 47 | 48 | -------------------------------------------------------------------------------- /src/org/apache/commons/io/serialization/ClassNameMatcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package org.apache.commons.io.serialization; 20 | 21 | /** 22 | * An object that matches a Class name to a condition. 23 | */ 24 | public interface ClassNameMatcher { 25 | 26 | /** 27 | * Returns true if the supplied class name matches this object's condition. 28 | * 29 | * @param className fully qualified class name 30 | * @return true if the class name matches this object's condition 31 | */ 32 | boolean matches(String className); 33 | } -------------------------------------------------------------------------------- /src/org/apache/commons/io/serialization/FullClassNameMatcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package org.apache.commons.io.serialization; 20 | 21 | import java.util.Arrays; 22 | import java.util.Collections; 23 | import java.util.HashSet; 24 | import java.util.Set; 25 | 26 | /** 27 | * A {@link ClassNameMatcher} that matches on full class names. 28 | *

29 | * This object is immutable and thread-safe. 30 | *

31 | */ 32 | final class FullClassNameMatcher implements ClassNameMatcher { 33 | 34 | private final Set classesSet; 35 | 36 | /** 37 | * Constructs an object based on the specified class names. 38 | * 39 | * @param classes a list of class names 40 | */ 41 | public FullClassNameMatcher(final String... classes) { 42 | classesSet = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(classes))); 43 | } 44 | 45 | @Override 46 | public boolean matches(final String className) { 47 | return classesSet.contains(className); 48 | } 49 | } -------------------------------------------------------------------------------- /src/org/apache/commons/io/serialization/RegexpClassNameMatcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package org.apache.commons.io.serialization; 20 | 21 | import java.util.regex.Pattern; 22 | 23 | /** 24 | * A {@link ClassNameMatcher} that uses regular expressions. 25 | *

26 | * This object is immutable and thread-safe. 27 | *

28 | */ 29 | final class RegexpClassNameMatcher implements ClassNameMatcher { 30 | 31 | private final Pattern pattern; // Class is thread-safe 32 | 33 | /** 34 | * Constructs an object based on the specified regular expression. 35 | * 36 | * @param regex a regular expression for evaluating acceptable class names 37 | */ 38 | public RegexpClassNameMatcher(final String regex) { 39 | this(Pattern.compile(regex)); 40 | } 41 | 42 | /** 43 | * Constructs an object based on the specified pattern. 44 | * 45 | * @param pattern a pattern for evaluating acceptable class names 46 | * @throws IllegalArgumentException if pattern is null 47 | */ 48 | public RegexpClassNameMatcher(final Pattern pattern) { 49 | if (pattern == null) { 50 | throw new IllegalArgumentException("Null pattern"); 51 | } 52 | this.pattern = pattern; 53 | } 54 | 55 | @Override 56 | public boolean matches(final String className) { 57 | return pattern.matcher(className).matches(); 58 | } 59 | } -------------------------------------------------------------------------------- /src/org/apache/commons/io/serialization/WildcardClassNameMatcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | package org.apache.commons.io.serialization; 20 | 21 | import org.apache.commons.io.FilenameUtils; 22 | 23 | /** 24 | * A {@link ClassNameMatcher} that uses simplified regular expressions 25 | * provided by {@link org.apache.commons.io.FilenameUtils#wildcardMatch(String, String) FilenameUtils.wildcardMatch} 26 | *

27 | * This object is immutable and thread-safe. 28 | *

29 | */ 30 | final class WildcardClassNameMatcher implements ClassNameMatcher { 31 | 32 | private final String pattern; 33 | 34 | /** 35 | * Constructs an object based on the specified simplified regular expression. 36 | * 37 | * @param pattern a {@link FilenameUtils#wildcardMatch} pattern. 38 | */ 39 | public WildcardClassNameMatcher(final String pattern) { 40 | this.pattern = pattern; 41 | } 42 | 43 | @Override 44 | public boolean matches(final String className) { 45 | return FilenameUtils.wildcardMatch(className, pattern); 46 | } 47 | } -------------------------------------------------------------------------------- /src/org/apache/commons/io/serialization/package.html: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 |

21 | This package provides a framework for controlling the deserialization of classes. 22 |

23 | 24 | 25 | --------------------------------------------------------------------------------