package com.javaranch.common ; import java.io.* ; import java.util.* ; import java.text.* ; /** Contains a collection of static methods related to files.

- - - - - - - - - - - - - - - - -

Copyright (c) 1998-2000 Paul Wheaton

You are welcome to do whatever you want to with this source file provided that you maintain this comment fragment (between the dashed lines). Modify it, change the package name, change the class name ... personal or business use ... sell it, share it ... add a copyright for the portions you add ...

My goal in giving this away and maintaining the copyright is to hopefully direct developers back to JavaRanch.

The original source can be found at JavaRanch

- - - - - - - - - - - - - - - - -

@author Paul Wheaton @author Carl Trusiak */ public class Files { private Files(){} // just to make sure someone doesn't try to instantiate this.

/** All of a text file is read in and stored in a Vector.

@param FileName The name of the text file to read in.

@exception IOException

@return The Vector where each object in the Vector contains one line from the text file.

*/ public static Vector fileToVector( String FileName ) throws IOException { Vector V = new Vector( 100 ); TextFileIn F = new TextFileIn( FileName ); String S; while( ( S = F.readLine() ) != null ) { V.addElement( S ); } F.close(); return V ; } /** All of a text file is read in and stored in a String array.

@param FileName The name of the text file to read in.

@exception IOException

@return The String array where each String contains one line from the text file.

*/ public static String[] fileToArray( String FileName ) throws IOException { Vector V = fileToVector( FileName ); String[] A = new String[ V.size() ]; V.copyInto( A ); return A ; } /** All of a String array is written out to a text file.

@param S The array of String objects to be written out.

@param FileName The name of the text file to write.

@exception IOException

*/ public static void arrayToFile( String[] S , String FileName ) throws IOException // write the array to the text file { TextFileOut F = new TextFileOut( FileName ); int I; for( I = 0 ; I < S.length ; I++ ) { F.writeLine( S[ I ] ); } F.close(); } /** Delete a specific file.

If the file does not exist, nothing is done.

*/ public static void delete( String fileName ) { File f = new File( fileName ); f.delete(); } /** Change the file name.

If dest already exists, it is deleted.

*/ public static void rename( String source , String dest ) { delete( dest ); File f = new File( source ); f.renameTo( new File( dest ) ); } /** Write one object to a file.

If the file already exists, it is overwritten.

@return true if file write successful.

*/ public static boolean writeObject( String fileName , Object obj ) { boolean returnVal = false ; try { ObjectOutputStream f = new ObjectOutputStream( new FileOutputStream( fileName ) ); f.writeObject( obj ) ; f.close(); returnVal = true ; } catch( Exception e ) { System.out.println( "could not write file " + fileName + ": " + e ); } return returnVal ; } /** Read one object from a file.

@return object or null if file read unsuccessful.

*/ public static Object readObject( String fileName ) { Object returnVal = null ; try { ObjectInputStream f = new ObjectInputStream( new FileInputStream( fileName ) ); try { returnVal = f.readObject() ; } finally { f.close(); } } catch( Exception e ) { System.out.println( "could not read file " + fileName + ": " + e ); } return returnVal ; } /** Read a file from the disk into a byte array.

Will throw an IOException if one is encountered.

@param filename The name of the file to read.

@return A byte array that is the exact same size as the file.

@exception IOException */ public static byte[] fileToByteArrayE( String filename ) throws IOException { byte[] returnVal = null ; RandomAccessFile f = new RandomAccessFile( filename , "r" ); byte[] buffy = new byte[ (int)f.length() ]; f.read( buffy ); f.close(); returnVal = buffy ; return returnVal ; } /** Read a file from the disk into a byte array.

If an IOException is encountered, a message is printed to STDOUT and null is returned.

@param filename The name of the file to read.

@return A byte array that is the exact same size as the file.

*/ public static byte[] fileToByteArray( String filename ) { byte[] returnVal = null ; try { returnVal = fileToByteArrayE( filename ); } catch( IOException e ) { System.out.println( "error reading file " + filename + ": " + e ); } return returnVal ; } public static void byteArrayToFile( byte[] data , String filename ) throws IOException { FileOutputStream out = new FileOutputStream( filename ); out.write( data ); out.close(); } /** Return a string array containing the current directory.

Directories will have angle brackets.

If there is a parent directory, the first entry will be a .. directory.

*/ public static String[] getDirectory( File f ) { boolean hasParent = ( f.getParent() != null ); String[] original = f.list(); String[] s ; // where the new string array will be int offset = 0 ; // if there is a parent, the offset will bump up one to make room for <..> if ( hasParent ) { offset++ ; s = new String[ original.length + 1 ]; s[0] = "<..>"; } else { s = new String[ original.length ]; } for( int i = 0 ; i < original.length ; i++ ) { String filename = original[ i ]; File tempFile = new File( f , filename ); if ( tempFile.isDirectory() ) { filename = "<" + filename + ">"; } s[ i + offset ] = filename ; } return s ; } /** Return a string array containing the current directory with timestamps and file sizes.

Directories will have angle brackets.

If there is a parent directory, the first entry will be a .. directory.

*/ public static String[] getDirectoryDetails( File f ) { // create two arrays: s contains the filenames and details contains the timestamps and file sizes. // After the arrays are created, create one nice looking string array and return that. boolean hasParent = ( f.getParent() != null ); // When running Netscape on Win95, "C:\" is apparently not a directory, but "C:\." is Str temp = new Str( f.toString() ); if ( temp.getLast() == '\\' ) { temp.append( '.' ); f = new File( temp.toString() ); } String[] original = f.list(); String[] s ; // where the new string array will be String[] details ; int offset = 0 ; // if there is a parent, the offset will bump up one to make room for <..> if ( hasParent ) { offset++ ; s = new String[ original.length + 1 ]; details = new String[ original.length + 1 ]; s[0] = "<..>"; details[0] = ""; } else { s = new String[ original.length ]; details = new String[ original.length ]; } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss "); int longestFilename = 4 ; int longestDetail = 0 ; for( int i = 0 ; i < original.length ; i++ ) { String filename = original[ i ]; String detail = ""; File tempFile = new File( f , filename ); if ( tempFile.isDirectory() ) { filename = "<" + filename + ">"; } else { Date d = new Date( tempFile.lastModified() ); detail = dateFormat.format( d ) + Str.commaStr( tempFile.length() ); } longestFilename = Math.max( longestFilename , filename.length() ); longestDetail = Math.max( longestDetail , detail.length() ); s[ i + offset ] = filename ; details[ i + offset ] = detail ; } // mash the details into s for( int i = 0 ; i < s.length ; i++ ) { Str str = new Str( s[ i ] ); // left align the names str.left( longestFilename + 1 ); Str detail = new Str( details[ i ] ); if ( detail.length() > 0 ) { // right align the file size int spacesToInsert = longestDetail - detail.length(); if ( spacesToInsert > 0 ) { detail.insert( Str.spaces( spacesToInsert ) , 19 ); } str.append( detail ); str.append( ' ' ); } s[ i ] = str.toString(); } return s ; } public static void copy( InputStream in , OutputStream out ) throws Exception { int bufferSize = 64 * 1024 ; byte[] buffy = new byte[ bufferSize ]; boolean done = false ; while( ! done ) { int bytesRead = in.read( buffy ); if ( bytesRead == -1 ) { done = true ; } else { out.write( buffy , 0 , bytesRead ); if ( bytesRead < bufferSize ) { done = true ; } } } in.close(); out.close(); } public static boolean appendText( String filename , String text ) { boolean returnVal = false ; try { TextFileOut out = new TextFileOut( filename , true ); out.println( text ); out.close(); returnVal = true ; } catch ( Exception e ) {} return returnVal ; } /** All of a text file is read in and unique Strings are stored in a String array.

@param FileName The name of the text file to read in.

@exception IOException

@return The String array where each String contains one unique line from the text file.

*/ public static String[] fileToUniqueArray( String FileName ) throws IOException { HashSet H = fileToHashSet( FileName ); String[] A = new String[ H.size() ]; A = (String[])H.toArray( A ); return A ; } /** All of a text file is read in and unique elements are stored in a HashSet.

@param FileName The name of the text file to read in.

@exception IOException

@return The HashSet where each element contains one unique line from the text file.

*/ public static HashSet fileToHashSet( String FileName ) throws IOException { TextFileIn F = new TextFileIn( FileName ); String S ; HashSet H = new HashSet(); while( ( S = F.readLine() ) != null ) { H.add( S ); } return H ; } /** Provided for testing purposes only.

*/ public static void unitTest( TestLog log ) { // xxx need tests } }