import java.io.*;
import java.nio.channels.FileChannel;
public class FileCopy
{
public static void main( String[] args ) throws IOException
{
if( 2 != args.length )
System.out.println( "Error: Parameter missing:\n java FileCopy InputFile OutputFile\n" );
else
copy( args[0], args[1], false, false );
}
// Seit Java JDK 1.4 bevorzugte und schnellere Methode
public static void copySinceJava14( File fin, File fout, boolean append ) throws IOException
{
FileChannel inChannel = new FileInputStream( fin ).getChannel();
FileChannel outChannel = new FileOutputStream( fout, append ).getChannel();
try {
inChannel.transferTo( 0, inChannel.size(), outChannel );
} finally {
if( inChannel != null ) try { inChannel.close(); } catch( IOException ex ) {/*ok*/}
if( outChannel != null ) try { outChannel.close(); } catch( IOException ex ) {/*ok*/}
}
}
// Bis Java JDK 1.3 zu verwendende Methode
public static void copyUptoJava13( File fin, File fout, boolean append ) throws IOException
{
int len = 32768;
byte[] buff = new byte[(int) Math.min( len, fin.length() )];
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream( fin );
fos = new FileOutputStream( fout, append );
while( 0 < (len = fis.read( buff )) )
fos.write( buff, 0, len );
} finally {
try { if( fos != null ) fos.close(); } catch( IOException ex ) {/*ok*/}
try { if( fis != null ) fis.close(); } catch( IOException ex ) {/*ok*/}
}
}
// Zusaetzliche Fehlerueberpruefungen
public static void copy( String fromFileName, String toFileName,
boolean overwriteIfExists, boolean append ) throws IOException
{
File fromFile = new File( fromFileName );
File toFile = new File( toFileName );
if( !fromFile.exists() )
throw new IOException( "Fehler: Quelldatei fehlt: " + fromFileName );
if( !fromFile.isFile() )
throw new IOException( "Fehler: Quelle ist ein Verzeichnis: " + fromFileName );
if( !fromFile.canRead() )
throw new IOException( "Fehler: Keine Leseberechtigung fuer Quelldatei: " + fromFileName );
if( toFile.isDirectory() )
toFile = new File( toFile, fromFile.getName() );
if( toFile.exists() ) {
if( !overwriteIfExists && !append )
throw new IOException( "Fehler: Zieldatei existiert bereits: " + toFileName );
if( !toFile.canWrite() )
throw new IOException( "Fehler: Keine Schreibberechtigung fuer Zieldatei: " + toFileName );
} else {
String parent = toFile.getParent();
if( parent == null )
parent = System.getProperty( "user.dir" );
File dir = new File( parent );
if( !dir.exists() )
throw new IOException( "Fehler: Zielverzeichnis existiert nicht: " + parent );
if( dir.isFile() )
throw new IOException( "Fehler: Ziel ist kein Verzeichnis: " + parent );
if( !dir.canWrite() )
throw new IOException( "Fehler: Keine Schreibberechtigung fuer Zielverzeichnis: " + parent );
}
copySinceJava14( fromFile, toFile, append );
}
}
import java.io.File;
public class GetFilesInDir
{
public static void main( String[] args )
{
System.out.println( "Zeige alle Dateien in einem Verzeichnis und den Unterverzeichnissen.\r\n" +
"Basisverzeichnis muss als Kommandozeilenparameter uebergeben werden.\r\n" );
if( args == null || args.length != 1 ) { return; }
System.out.println( getFilesInDirToString( args[0], null, null, null ) );
}
public static String getFilesInDirToString( String dir, String spacesStart, String spacesAdd, String lineSeparator )
{
if( lineSeparator == null ) { lineSeparator = System.getProperty( "line.separator" ); }
if( spacesStart == null ) { spacesStart = ""; }
if( spacesAdd == null ) { spacesAdd = " "; }
if( dir == null || dir.trim().length() == 0 ) {
return lineSeparator + "Fehler: Verzeichnis muss uebergeben werden." + lineSeparator;
}
File[] entries = (new File( dir )).listFiles();
if( entries == null ) {
return lineSeparator + "Fehler: '" + dir + "' ist kein Verzeichnis." + lineSeparator;
}
if( entries.length == 0 ) {
return spacesStart + "'" + dir + "' enthaelt keine Dateien oder Verzeichnisse." + lineSeparator;
}
StringBuffer sb = new StringBuffer( "" );
for( int i = 0; i < entries.length; i++ ) {
if( entries[i].isFile() ) {
sb.append( spacesStart ).append( entries[i] ).append( lineSeparator );
}
}
for( int i = 0; i < entries.length; i++ ) {
if( entries[i].isDirectory() ) {
sb.append( lineSeparator )
.append( spacesStart ).append( "Verzeichnis " ).append( entries[i].toString() ).append( lineSeparator )
.append( getFilesInDirToString( entries[i].toString(), spacesStart + spacesAdd, spacesAdd, lineSeparator ) );
}
}
return sb.toString();
}
}
import java.io.*;
import java.util.zip.*;
public class ZipTest
{
/**
* Zip: Einen InputStream in einen OutputStream zippen.
* Wichtig: Auf beide Streams muss die close()-Methode aufgerufen werden.
* @param instreamForZip InputStream, der gezipped werden soll.
* @param outstreamZipped OutputStream, gezipped.
* @param origFilename Originaldateiname (wird in der Zipdatei gespeichert).
*/
public static void zipStream( InputStream instreamForZip, OutputStream outstreamZipped, String origFilename ) throws IOException
{
byte[] buf = new byte[65536];
int len;
ZipOutputStream zout = new ZipOutputStream( new BufferedOutputStream( outstreamZipped ) );
zout.putNextEntry( new ZipEntry( origFilename ) );
while( (len = instreamForZip.read( buf )) > 0 ) {
zout.write( buf, 0, len );
}
zout.closeEntry();
zout.finish();
zout.flush();
}
public static void main( String[] args ) throws IOException
{
String origFilename = "MeineDatei.txt";
String meinText = "BlaBlupp äöüß\u20AC";
String encoding = "UTF-8";
// Mit ByteArray:
InputStream isForZip = new ByteArrayInputStream( meinText.getBytes( encoding ) );
OutputStream osZipped = new ByteArrayOutputStream();
zipStream( isForZip, osZipped, origFilename );
// ... System.out.println( osZipped );
isForZip.close();
osZipped.close();
// Mit Dateien:
BufferedWriter out = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( origFilename ), encoding ) );
try { out.write( meinText ); } finally { out.close(); }
isForZip = new FileInputStream( origFilename );
osZipped = new FileOutputStream( origFilename + ".zip" );
zipStream( isForZip, osZipped, origFilename );
isForZip.close();
osZipped.close();
}
}
Ab Java 7 gibt es weitere File-I/O-Klassen und -Methoden, die vieles vereinfachen, zum Beispiel: FileSystems.getDefault(), Path.getFileSystem(), Path.deleteIfExists(), Path.copyTo(), Path.moveTo(), Path.newDirectoryStream(), Files.walkFileTree(), FileVisitor, BasicFileAttributes, WatchService, Path.register(), Path.checkAccess(), AsynchronousFileChannel (siehe bei OpenJDK oder Oracle).
Beachten Sie, dass es die Klasse FileSystem ab Java 7 doppelt gibt: als abstrakte (normalerweise nicht sichtbare) java.io.FileSystem und als java.nio.file.FileSystem.