📄 cbutility.java
字号:
package com.ca.commons.cbutil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This is a grab bag of useful classes and static functions that are
* not important enough to merit being top level entities. Most of them
* are concerned with string handling, file handling, and i18n issues.
*/
public class CBUtility
{
private static Cursor savedCursor;
private static Frame displayFrame = null;
private static Logger log = Logger.getLogger(CBUtility.class.getName());
private CBUtility()
{
}
/**
* A utility ftn used to make a closing window shut down
* the current application. Useful for small test progs.
*/
public static class BasicWindowMonitor extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
Window w = e.getWindow();
w.setVisible(false);
w.dispose();
//System.exit(0);
}
}
/**
* Returns the raw text (i.e. with tags as "\<...\>" strings) of a web page
*
* @param url the url of the web age to read as plain text.
* @return a StringBuffer containing the raw html text
*/
public static StringBuffer readURLText(URL url)
{
return readURLText(url, new StringBuffer("error: can't read URL " + url.toString()));
}
/**
* Returns the raw text (i.e. with tags as "\<...\>" strings) of a web page
*
* @param url the url of the web age to read as plain text.
* @param errorText a custom message to return if something goes wrong.
* @return a StringBuffer containing the raw html text
*/
public static StringBuffer readURLText(URL url, StringBuffer errorText)
{
StringBuffer page = new StringBuffer("");
String thisLine;
try
{
BufferedReader source = new BufferedReader(new InputStreamReader(url.openStream()));
while ((thisLine = source.readLine()) != null)
{
page.append(thisLine + "\n");
}
return page;
}
catch (Exception e)
{
return errorText;
}
}
/**
* Reads an input stream into a byte array.
*/
public static byte[] readStream(InputStream is) throws IOException
{
byte[] data = null;
byte[] buffer = new byte[16384];
int blockSize = 0;
int size = 0;
while ((blockSize = is.read(buffer)) != -1) // kinda clumsy, reallocating
{ // memory like this I guess,
byte[] temp = new byte[size + blockSize]; // but since we don't know
if (size != 0) // how big the stream is, what
System.arraycopy(data, 0, temp, 0, size); // else can we do? (?)
System.arraycopy(buffer, 0, temp, size, blockSize);
data = temp;
size += blockSize;
}
return data;
}
/**
* Reads a text file, and returns the result as a String. Not
* Recommended for large (say > 100k) files.
*
* @param file the ascii file to read from.
*/
public static String readTextFile(File file)
throws IOException
{
// special handling for file reading in non-english locales...
if (Locale.getDefault().getLanguage().equals("en") == false)
return readI18NFile(file);
// Read File into String Buffer
FileReader in = new FileReader(file);
int size = (int) file.length();
char[] data = new char[size];
int chars_read = 0;
while (chars_read < size)
chars_read += in.read(data, chars_read, size - chars_read);
return new String(data); // use default locale encoding...
}
/**
* Reads a text file, and returns the result as a StringBuffer. Not
* Recommended for large (say > 100k) files.<p>
* <p/>
* This function attempts to automatically determine the encoding
* of the file it is to read, as either UTF-16, UTF-8, or default
* locale encoding, based on 1) whether the first two bytes are
* Unicode byte-ordering markers ('FFFE' or 'FEFF'), UTF-8 (based
* on whether the file is a valid UTF8 string) or,
* failing this, the default locale encoding.
*
* @param file the local encoding/unicode/utf8 file to read from.
*/
public static String readI18NFile(File file)
throws IOException
{
// Read File into String Buffer
FileInputStream in = new FileInputStream(file);
int size = (int) file.length();
byte[] data = new byte[size];
int bytes_read = 0;
while (bytes_read < size)
bytes_read += in.read(data, bytes_read, size - bytes_read);
return readI18NByteArray(data);
}
public static String readI18NByteArray(byte[] data)
{
// Try to work out whether this is unicode double bytes (utf-16),
// unicode (or *cough* 7 bit ascii) in utf-8 format, or local
// encoding...
try
{
if (CBParse.isUnicode(data))
{
log.finer("reading unicode 16 bit text");
String text = new String(data, "UTF-16"); // return as 16 bit unicode
if (text.length() > 0) return text;
return new String(data); // something went wrong - try again with default encoding...
}
else
{
byte[] test = new byte[250]; // grab the start of the file to test...
if (data.length < 250)
test = data;
else
System.arraycopy(data, 0, test, 0, 250);
if (CBParse.isNonAsciiUTF8(test))
{
log.finer("reading utf8 text");
String text = new String(data, "UTF-8"); // return as UTF-8
if (text.length() > 0) return text;
return (new String(data)); // something went wrong - try again with default encoding
}
else
{
log.finer("reading local encoding text");
String newString = new String(data);
if (newString.indexOf("\\u") == -1)
{
return newString; // no need for special processing.
}
// MANUALLY (!) decode \ u java unicode escape strings...
// (Why? Because someone may be in a foreign locale, but
// still using broken java unicode escape syntax from standard
// property files.)
StringBuffer buffer = new StringBuffer(newString);
int pos = 0;
while (pos + 6 < buffer.length())
{
if (buffer.charAt(pos) != '\\')
pos++;
else if (buffer.charAt(pos + 1) != 'u')
pos += 2;
else
{
String unicode = buffer.substring(pos + 2, pos + 6);
int uni = Integer.parseInt(unicode, 16);
buffer = buffer.delete(pos, pos + 6);
buffer = buffer.insert(pos, (char) uni);
pos++;
}
}
return buffer.toString(); // return as default locale encoding
}
}
}
/* If anything goes wrong (UnsupportedEncodingException, or hopefully if
* the utf-8 string turns out not to be) fall back on using the
* default encoding.
*/
catch (Exception e)
{
log.warning("Confused Reading File: " + e.toString() + "\n -> reverting to default encoding");
return new String(data); // return as default locale encoding
}
}
/**
* Reads an array of strings from a file
* (via a property file, 'cause I'm lazy).
*
* @param fileName the file to read from
*/
public static String[] readStringArrayFile(String fileName)
{
Properties props = readPropertyFile(fileName);
String[] values = new String[props.size()];
Enumeration en = props.elements();
int count = 0;
while (en.hasMoreElements())
{
values[count++] = en.nextElement().toString();
}
return values;
}
/**
* Reads a java Properties list from a file.
*
* @param fileName the full path and file name of the properties file
* to read in.
*/
public static Properties readPropertyFile(String fileName)
{
Properties propertyList = new Properties();
try
{
File propertyFile = new File(fileName);
if (propertyFile == null || propertyFile.exists() == false)
{
log.warning("No property list:\n" + fileName);
return propertyList; // return empty properties list
}
FileInputStream in = new FileInputStream(propertyFile);
propertyList.load(in);
return propertyList;
}
catch (Exception e)
{
log.log(Level.WARNING, "Can't read property list:\n" + fileName + "\n", e);
return propertyList;
}
}
/**
* Writes an array of strings into a file
* (via a property file, 'cause I'm lazy).
* (XXX Warning - will only write unique values; doubles will be lost).
*
* @param fileName the file to read to
* @param strings the array of strings
*/
public static void writeStringArrayFile(String fileName, String[] strings)
{
Properties props = new Properties();
for (int i = 0; i < strings.length; i++)
props.put(strings[i], strings[i]); // so it's redundant. sue me.
writePropertyFile(fileName, props, "generated string array list");
}
/**
* Writes a java Properties list to a file.
*
* @param fileName the full path and file name of the properties file
* to read in.
*/
public static void writePropertyFile(String fileName, Properties propertyList, String comments)
{
// do hack to get propertyList to print out in alphabetical order...
CBProperties orderedPropertyList = new CBProperties(propertyList);
try
{
File propertyFile = new File(fileName);
FileOutputStream out = new FileOutputStream(propertyFile);
orderedPropertyList.store(out, "Generated Property List " + fileName + "\n" + ((comments != null) ? comments : ""));
}
catch (Exception e)
{
log.log(Level.WARNING, "Can't write property list:\n" + fileName + "\n", e);
}
}
/**
* Turns a string into HTML displayable text by escaping
* special characters ('<','&' etc...).
* <p/>
* ... add new ones as required; or see if an existing ftn somewhere
* does this already...
*
* @deprecated use CBParse method instead
*/
public static String toHTML(String rawText)
{
String test;
if (rawText.length() > 14)
test = rawText.substring(0, 14).toLowerCase();
else
test = rawText.toLowerCase();
if (test.startsWith("<html>") || test.startsWith("<!doctype html>"))
{
// XXX this was commented out, but it seems to be necessaary/desirable?
if (test.startsWith("<html>"))
rawText = rawText.substring(6);
else if (test.startsWith("<!doctype html>"))
rawText = rawText.substring(15);
if (rawText.toLowerCase().endsWith("</html>"))
{
rawText = rawText.substring(0, rawText.length() - 7);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -