📄 filehandler2.java
字号:
//**************************************
// Name: Universal File Handler
// Description:There is a lot you can do with this class! See the code to see the exact methods and how they work. You can delete files, copy files, insert a line into a file (alphabetically or append at end), search for a line, retrieve the nth line as a String, count the number of lines in the files, and more!
// By: Jennica Jane Humphrey
//
//
// Inputs:None
//
// Returns:None
//
//Assumes:Simply paste the code below into a file, UniversalFileHandler.java... you have to configure two variables to make sure the files will to go to the directory you want them to go to. To use the code, create a new instance in another class... like UniversalFileHandler uFileHandler = new UniversalFileHandler();
//
//Side Effects:None
//This code is copyrighted and has limited warranties.
//Please see http://www.Planet-Source-Code.com/xq/ASP/txtCodeId.2417/lngWId.2/qx/vb/scripts/ShowCode.htm
//for details.
//**************************************
import java.io.*;
class UniversalFileHandler {
/**********************************************************
*
* UNIVERSAL FILE HANDLER
* UniversalFileHandler.java
*
* The goal here is to be as encapsulated as possible.
* This class should be reuseable for a wide variety of
* purposes and have no "specialization" whatsoever
* for my particular applications.
*
* Does various things with files. Like, delete,
* create, insert a line into a file in lexiconial
* order and all that.
*
*********************************************************
*
* CUSTOMIZING IT FOR YOUR USE
*
* All you need to do is modify the filePath and
* the fileSlash variables at the end of the class.
*
* FILEPATH: The directory you want to place the
* files in.
*
* FILESLASH: Windows users should
* keep the fileSlash variable unchanged at "\\".
* Linux probably should change the variable to
* "/".
*
*********************************************************
*
* METHODS INCLUDED IN THIS CLASS
*
* There is a lot you can do with this class! Here are
* the methods, as they appear in this class (see the
* actual methods themselves to find out how to use them):
*
* deleteFile: Deletes a file.
*
* createFile: Creates a (blank) file.
*
* fileExists: Checks to see if a file exists.
*
* copyFile: Copies the original file into a new file.
*
* searchForString: Searches for a partial string in the
* file at the beginning of a new line.
*
* numberOfLines: Returns the number of lines in a given
* file.
*
* returnFullString: Returns the full line of a partial
* string at the beginning of a line (ie, if you search for
* "ABC", you'll get "ABCDEFGHIJKLMNOPQRSTUVWXYZ" returned)
*
* retrieveEndLineChar: Returns the last character in a
* specified line in the file.
*
* writeIntoFile: Writes a line at the end of the file.
*
* insertIntoFile: Inserts a line in the file in
* alphabetical order.
*
* deleteFromFile: Deletes a single line from the file.
*
* getLine: Returns the nth line from the file.
*
***********************************************************
*
* If you see any errors in this code, please contact
* me at emelia2002@hotmail.com. Please keep the comments
* on this java file unchanged and keep my name and email.
*
* I created this class for a school project and it just
* kept growing and growing... I hope people will get as
* much use out of this as I have.
*
* Feel free to use this class in whatever way you want.
* I've used it with almost all of my applications that
* relate to file manipulation... it has been a great
* timesaver. My java knowledge is largely self-taught,
* so please pardon any gaffes I make.
*
* @seeRandomAccessFile
* @seeFile
* @author Jennica Humphrey (emelia2002@hotmail.com)
* @version %I%, %G%
* @since JDK1.3
*
*/
/**
* Deletes the file if it does already exist.
*
* @param fileName Name of the file to be deleted.
* @seeFile
* @sinceJDK1.3
*/
public void deleteFile(String fileName) {
String path = new String();
path = filePath; // uses the filePath directory
File f1 = new File( path, fileName);
if (f1.exists())
f1.delete();
} // Ends deleteFile
/**
* Creates the file if it does already exist.
*
* @param fileName Name of the file to be deleted.
* @returnTRUE if file is successfully created,
*FALSE if it already exists or if some
* other error happens.
* @seeFile
* @sinceJDK1.3
*/
public boolean createFile(String fileName) {
String path = new String();
path = filePath; // uses the filePath directory
boolean fileCreated = false;
File f1 = new File( path, fileName);
if ( !f1.exists() ) {
try {
f1.createNewFile();
fileCreated = true;
}
catch( IOException e ) {
}
}
return fileCreated;
} // Ends createFile
/**
* Checks to see if a file exists.
*
* @param fileName Name of the file to be deleted.
* @returnTRUE if the file exists, FALSE if the file
*does not exist.
* @seeFile
* @sinceJDK1.3
*/
public boolean fileExists(String fileName) {
// Makes sure file exists
String path = new String();
path = filePath; // Uses the filePath dir
boolean fileFound = false;
File f1 = new File(path, fileName);
if (f1.exists())
fileFound = true;
return fileFound;
} // ends fileExists
/**
* Copies a file (assuming it exists) into a new file.
*
* @param fileNameName of the file to be copied.
* @param copiedFileName Name of the file to be written into.
* @see RandomAccessFile
* @see#fileExists
* @see#createFile
* @sinceJDK1.3
*/
public void copyFile(String fileName, String copiedFileName) {
// Copies one file into a new file (if that file doesn't exist )
if ( fileExists(fileName) ) // Creates new file if original file does exist
createFile( copiedFileName );
if ( fileExists(fileName) ) { // If original file exists, copy file into new file
try {
fileName = filePath + fileSlash + fileName;
copiedFileName = filePath + fileSlash + copiedFileName;
RandomAccessFile raf = new RandomAccessFile(fileName, "r");
RandomAccessFile raf2 = new RandomAccessFile(copiedFileName, "rw");
raf.seek( 0 );
raf2.seek( 0 );
Long lengthFile = new Long( raf.length() );
byte[] b = new byte[ lengthFile.intValue() ];
raf.readFully(b);
raf2.write(b);
raf.close();
}
catch (IOException e) {
System.out.println("Error opening file: " + e);
}
}
} // Ends copyFile
/**
* Searches for a partial string at the beginning of a new line
* in a file name. For instance, searching for "ABC" in a file
* with the line "ABCDEFGHIJKL" will return TRUE, but searching
* for "BCD" will not return TRUE.
*
* Does not assume lines are in alphabetical order.
*
* @param fileName Name of the file to be searched
* @param searchString Partial string to be searching for.
* @returnTRUE if there is a match for the string being
*searched for, FALSE if there is no match.
* @see RandomAccessFile
* @sinceJDK1.3
*/
public boolean searchForString(String fileName, String searchString) {
int i;
long filePointer;
boolean stringFound = false;
fileName = filePath + fileSlash + fileName;
try {
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
raf.seek( 0 ); // Starts at the beginning of the file
String thisString = new String();
do {
thisString = raf.readLine();
if ( thisString.length() > searchString.length() )
thisString = thisString.substring( 0, searchString.length() );
i = searchString.compareToIgnoreCase( thisString );
if ( i == 0 )
stringFound = true;
} while ( raf.getFilePointer() < raf.length() );
raf.close();
}
catch (IOException e) {
System.out.println("Error opening file: " + e);
}
return stringFound;
} // ends searchForString
/**
* Returns the number of lines in a given file.
*
* @param fileName File to check for.
* @returnThe number of lines within a file.
* @seeRandomAccessFile
* @sinceJDK1.3
*/
public int numberOfLines( String fileName ) {
int lineCount = 0;
fileName = filePath + fileSlash + fileName;
try {
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
raf.seek( 0 );
if ( raf.length() > 0 ) {
do {
lineCount++;
raf.readLine();
} while ( raf.getFilePointer() < raf.length() );
}
raf.close();
}
catch (IOException e) {
System.out.println("Error opening file: " + e);
}
return lineCount;
} // end lineCount
/**
* Returns the full string of a partial search. For example
* returnFullString( "jjh0901.txt", "abc" ) will return
* "abcFullLine".
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -