📄 filetools.java
字号:
//ByteArrayOutputStream byteOut = new ByteArrayOutputStream(fout);
BufferedInputStream bin = new BufferedInputStream(inputStream);
byte buf[] = new byte[BUFFER_SIZE];
int availableBytes;
while ((availableBytes = bin.read(buf)) > -1) {
streamOut.write(buf, 0, availableBytes);
}
bin.close();
inputStream.close();
streamOut.flush();
streamOut.close();
}
} catch (Exception e) {
//-------- silent catch -------------------
//log.error(e);
}
}
// simple method that saves the given string to the given filename
// any existing files are replaced
public static void saveToFileUtf8(String fname, String data) {
try {
makeDirectory(fname);
String filename = removeFileUrlPrefix(fname);
File file = new File(filename);
//File file = new File(new URI(setUrlPrefix(fname)));
FileOutputStream fout = new FileOutputStream(file);
OutputStreamWriter stream_out = new OutputStreamWriter(fout, "UTF-8");
stream_out.write(data);
stream_out.flush();
stream_out.close();
//log.debug("wrote in UTF-8: " + fname);
} catch (Exception e) {
e.printStackTrace();
}
}
// checks whether "line1" contains the suppstring "varName1" (without a preceeding #
// if not, null is returned otherwise "value1" is returned
public static String checkLine(String line1, String varName1, String value1) {
String ret = null;
line1.trim();
if (line1.startsWith("#") || line1.startsWith(";") ||
line1.startsWith("REM") || line1.startsWith("rem"))
return ret;
// create a substring without ending commends
StringTokenizer enumerator = new StringTokenizer(line1, "#", false);
String data = "";
if (enumerator.hasMoreElements())
data = (String) enumerator.nextElement();
data.trim();
//System.out.println("checking: <" + data + "> with <" + varName1 + ">");
if (data.startsWith(varName1)) {
ret = value1;
//System.out.println("Line replaced with <" + ret + ">");
}
return ret;
}
// read all lines from the input-file and sets the corresponding entry
// handles #13 and #10 right (DOS/UNIX files)
public static void setFileEntry(String Filename1, String a_section, String[] varName1, String[] value1)
throws java.io.IOException {
String currentSection = "";
File orgFile = new File(Filename1);
File tempFile = File.createTempFile("ini", ".tmp", orgFile.getParentFile());
//System.out.println("Tempfile: " + tempFile.getAbsolutePath());
// write all names to a list. Entries are removed, when they are updated
List updatedVars = new Vector(value1.length);
for (int i = 0; i < value1.length; i++)
updatedVars.add(value1[i]);
FileInputStream fis = new FileInputStream(orgFile);
//DataInputStream fin = new DataInputStream(fis);
InputStreamReader fin = new InputStreamReader(fis, "UTF-8");
BufferedReader in = new BufferedReader(fin);
FileOutputStream fos = new FileOutputStream(tempFile);
//DataOutputStream fout = new DataOutputStream(fos);
OutputStreamWriter fout = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter out = new BufferedWriter(fout);
String line = "";
//while (fin.available() > 0) {
while (line != null) {
// read a line
line = in.readLine();
//-------------------- now we have an input-line
//update the line if needed
if (line.startsWith("[")) {
// on a new section we write new variables at the end of the sectoin
if (currentSection.equalsIgnoreCase(a_section)) {
while (!updatedVars.isEmpty()) {
String str = (String) updatedVars.remove(0);
out.write(str + "\n");
}
}
currentSection = line.substring(1, line.length() - 1);
} else {
if (currentSection.equalsIgnoreCase(a_section)) {
for (int i = 0; i < varName1.length; i++) {
String newLine = checkLine(line, varName1[i], value1[i]);
if (newLine != null) {
// write the line with the new value
line = newLine;
if (updatedVars.contains(value1[i]))
updatedVars.remove(value1[i]);
}
} // end for
}
}
// write the line to the outputstream
out.write(line + "\n");
} // end while fin reading
// write new Variables at the end of the file
if (!updatedVars.isEmpty() && !currentSection.equalsIgnoreCase(a_section)) {
fout.write("\n");
String str = "[" + a_section + "]";
fout.write(str + "\n");
}
while (!updatedVars.isEmpty()) {
String str = (String) updatedVars.remove(0);
fout.write(str + "\n");
}
out.close();
fout.close();
fos.close();
in.close();
fin.close();
fis.close();
fin = null;
fis = null;
// delete the original file and rename the tempfile
replaceFile(Filename1, tempFile.getAbsolutePath(), true);
} // end method
public static void setFileEntry(String Filename1, String a_section, String a_varName, String a_value)
throws java.io.IOException {
String[] sectionArray = new String[1];
String[] varArray = new String[1];
String[] valueArray = new String[1];
sectionArray[0] = a_section;
varArray[0] = a_varName;
valueArray[0] = a_value;
setFileEntry(Filename1, a_section, varArray, valueArray);
}
// delete originalFila and rename newFile to originalFile-name
public static void replaceFile(String originalFile1, String newFile1,
boolean makeBackup1) {
// try {
File orgFile = new File(originalFile1);
File newFile = new File(newFile1);
//File tempFile = new File(orgFile.getName() + ".bak");
File tempFile = new File(originalFile1 + ".bak");
if (!newFile.exists()) {
System.err.println("File " + newFile.toString() + " does not exitst");
return;
}
// save the original file to .bak
if (orgFile.exists()) {
// prepare the tempFile (delete if exists)
if (makeBackup1) {
if (tempFile.exists()) {
if (!tempFile.delete()) {
System.err.println("could not delete file " + tempFile.toString());
return;
}
}
if (!orgFile.renameTo(tempFile)) {
System.err.println("\ncould not rename file " + orgFile.toString() +
" to " + tempFile.toString());
return;
}
} else {
if (!orgFile.delete()) {
System.err.println("could not delete file " + orgFile.toString());
return;
}
} // end if makeBackup
} // end if orgFile exists
if (!newFile.renameTo(orgFile)) {
System.err.println("could not rename file " + newFile.toString() +
" to " + orgFile.toString());
return;
}
// } catch {
// }
}
/**
* delete a single File called fileName.
* Note: placeholders like *.java are allowed
*/
public static void deleteFile(String fileName1) {
if ((fileName1 == null) || (fileName1.trim().length() == 0)) {
return;
}
try {
File orgFile = new File(fileName1);
if (orgFile.exists()) {
orgFile.delete();
}
} catch (Exception e) {
//log.error(e);
e.printStackTrace();
}
} // end method
/**
* @param path1 The pathname to parse
* @return a list with all path names. e.g. "/temp/dummy/joe.jpg" -> {"temp" ,"dummy", "joe"}
*/
public static String[] parsePathName(String path1) {
String[] returnValue = new String[0];
StringTokenizer tokens = new StringTokenizer(path1, "/\\", false);
returnValue = new String[tokens.countTokens()];
int counter = 0;
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken();
returnValue[counter] = token;
counter++;
} // end while
return returnValue;
}
/**
* retrieve a list of all subdirs in the path
*
* @param a_fileSettings containing the startdirectoy ind filter patterns
* @return a list of all mathing directoryies - no files
*/
public static String[] subDirList(FileParserSettings a_fileSettings) {
String path1 = a_fileSettings.getStartDirectoryList().get(0);
//log.debug("path: <" + path1 + ">");
String[] returnValue = new String[0];
if (path1 == null) {
return returnValue;
}
try {
File path = new File(FileTools.removeFileUrlPrefix(path1));
File[] list;
//list = path.listFiles();
list = path.listFiles((FileFilter) new DirFilter(a_fileSettings));
//list = path.listFiles((FileFilter) null);
if (list == null) {
list = new File[0];
}
List resultList = new Vector();
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
resultList.add(list[i].getName());
}
}
returnValue = (String[]) resultList.toArray(new String[resultList.size()]);
} catch (Exception e) {
//log.error(e);
e.printStackTrace();
}
return returnValue;
}
/**
* replace invalid characters filename that are not allowed in
* filenames. Note: ":" is replaced. so don't use it with absolute paths
* like "c:\test". The same is with "\", "/"
*/
public static String checkFilename(String filename1) {
String ret = filename1;
ret = ret.replace(':', '_');
ret = ret.replace('\\', '_');
ret = ret.replace('/', '_');
ret = ret.replace(';', '_');
ret = ret.replace('*', '_');
ret = ret.replace('?', '_');
ret = ret.replace('\"', '_');
ret = ret.replace('>', '_');
ret = ret.replace('<', '_');
ret = ret.replace('|', '_');
return ret;
}
/**
* retrieve the directory of the file. unchanged if it is a directory, otherwise the
* directory wihtout the filename
*/
public static String getFilePath(String file1) {
String returnValue = file1;
if (file1 == null) {
return "";
}
/*File path = new File(file1);
if (path.isFile()) {
returnValue = path.getPath();
}
returnValue = resolvePath(returnValue, true);*/
if (returnValue.endsWith("/") || returnValue.endsWith("\\")) {
return returnValue;
}
StringTokenizer tokens = new StringTokenizer(file1, "/\\", true);
String dummy = "";
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken();
if (tokens.hasMoreTokens()) {
dummy += token;
}
}
returnValue = dummy;
return returnValue;
}
/**
* retrieve the name of the file without the directory prefix.
* if it is a directory or null then "" is returned;
*/
public static String getFilename(String fileWithPath1) {
String returnValue = "";
if (fileWithPath1 == null || fileWithPath1.length() < 1) {
return returnValue;
}
try {
File file;
file = new File(fileWithPath1);
//if (file.isFile()) {
//returnValue = file.getName();
String path = getFilePath(fileWithPath1);
returnValue = fileWithPath1.substring(path.length());
//}
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
}
return returnValue;
}
/**
* input: path+filter, e.g. C:/temp/*.bak
* ouput: list with all matching files e.g. c:/temp/test.bak, .... - no directories
* Note: does not go recusive iinto subfolders
*/
public static String[] fileList(FileParserSettings a_fileSettings) {
//log.debug("path: <" + path1 + ">");
//log.debug("filter: <" + fileFilter1 + ">");
File path = new File(FileTools.removeFileUrlPrefix(a_fileSettings.getStartDirectoryList().get(0)));
String[] list;
list = path.list(new DirFilter(a_fileSettings));
if (list == null) {
list = new String[0];
}
//Arrays.sort(list, new AlphabeticComparator());
//for(int i = 0; i < list.length; i++)
return list;
}
/** return a list of all Files of in the subdirectory
* todo: recursive parsing is not cmpletly implemented
* @param fileSettings containing startdirs, filefilter, excludelist
* @param walkRecusive if true, subdirectories are scanned, too
* @return
*/
/*public static List fileList(FileParserSettings fileSettings, boolean walkRecusive) {
//log.debug("path: <" + path1 + ">");
//log.debug("filter: <" + fileFilter1 + ">");
List returnValue = new Vector(10, 100);
try {
List pathList = new Vector(0, 10);
for (String path : fileSettings.getFileFilterList()) {
pathList.add(setFinalDirectorySlash(path));
}
if (walkRecusive) {
String[] dirList = subDirList(path);
for (int i = 0; i < dirList.length; i++) {
String s = dirList[i];
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -