📄 textutils.java
字号:
String prefix = ""; while (str.length() > 80) { int i = 80; for( ; i > 0; i--) if (str.charAt(i) == ' ' || str.charAt(i) == ',') break; if (i <= 0) i = 80; if (str.charAt(i) == ',') i++; System.out.println(prefix + str.substring(0, i)); if (str.charAt(i) == ' ') i++; str = str.substring(i); prefix = " "; } System.out.println(prefix + str); }// /**// * Method to compare two names and give a sort order.// * The comparison considers numbers in numeric order so that the// * string "in10" comes after the string "in9".// *// * Formal definition of order.// * Lets insert in string's character sequence number at start of digit sequences.// * Consider that numbers in the sequence are less than chars.// *// * Examples below are in increasing order:// * "" { }// * "0" { 0, '0' }// * "9" { 9, '9' }// * "10" { 10, '1', '0' }// * "2147483648" { 2147483648, '2', '1', '4', '7', '4', '8', '3', '6', '4', '8' }// * " " { ' ' }// * "-" { '-' }// * "-1" { '-', 1, '1' }// * "-2" { '-', 2, '2' }// * "a" { 'a' }// * "a0" { 'a', 0, '0' }// * "a0-0" { 'a', 0, '0', '-', 0, '0' }// * "a00" { 'a', 0, '0', '0' }// * "a0a" { 'a', 0, '0', 'a' }// * "a01" { 'a', 1, '0', '1' }// * "a1" { 'a', 1, '1' }// * "in" { 'i', 'n' }// * "in1" { 'i', 'n', 1, '1' }// * "in1a" { 'i', 'n', 1, '1', 'a' }// * "in9" { 'i', 'n', 9, '9' }// * "in10" { 'i', 'n', 10, '1', '0' }// * "in!" { 'i', 'n', '!' }// * "ina" { 'i , 'n', 'a' }// *// * @param name1 the first string.// * @param name2 the second string.// * @return 0 if they are equal, nonzero according to order.// */// public static int nameSameNumeric(String name1, String name2) {// return STRING_NUMBER_ORDER.compare(name1, name2);// } /** * Method to set the string stored on the system clipboard. * @param text the new text for the clipboard. If text is null, the contents is clean. */ public static void setTextOnClipboard(String text) { // put the text in the clipboard java.awt.datatransfer.Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable transferable = new StringSelection(text); cb.setContents(transferable, null); } /** * Method for obtaining the string on the system clipboard. * @return the string on the system clipboard (returns a null string if nothing is found). */ public static String getTextOnClipboard() { String result = null; Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable contents = clipboard.getContents(null); if (contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { result = (String)contents.getTransferData(DataFlavor.stringFlavor); Transferable transferable = new StringSelection(null); } catch (UnsupportedFlavorException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * Method to convert a file path to a URL. * @param fileName the path to the file. * @return the URL to that file (null on error). */ public static URL makeURLToFile(String fileName) { if (fileName.startsWith("file://")) fileName = fileName.substring(6); if (fileName.startsWith("file:/")) fileName = fileName.substring(5); // fix file names with spaces encoded (for example "%20") try { fileName = URLDecoder.decode(fileName, "UTF-8"); } catch (UnsupportedEncodingException e) {} File file = new File(fileName); try { return file.toURI().toURL();// return file.toURL(); // deprecated in Java 1.6 } catch (java.net.MalformedURLException e) { System.out.println("Cannot find file " + fileName); } return null; } /** * Get the file for the URL. The code * <code> * new File(url.getPath()) * </code> * returns an illegal leading slash on windows, * and has forward slashes instead of back slashes. * This method generates the correct File using * <code> * new File(url.toURI()) * </code> * <P> * use <code>getPath()</code> on the returned File * to get the correct String file path. * <P> * This should only be needed when running an external process under * windows with command line arguments containing file paths. Otherwise, * the Java IO code does the correct conversion. * * @param url the URL to convert to a File. * @return the File. Will return null if * URL does not point to a file. */ public static File getFile(URL url) { try { return new File(url.toURI()); } catch (java.net.URISyntaxException e) { System.out.println("URL -> File conversion error: "+e.getMessage()); return new File(url.getPath()); } catch (java.lang.IllegalArgumentException e) { System.out.println("URL -> File conversion error: "+e.getMessage()); return null; } } /** * Method to convert a URL to a string. * @param url the URL * @return a String that is the path to that URL. */ private static String URLtoString(URL url) { String filePath = url.getFile(); // use proper URI to ensure valid path name try { URI uri = new URI(filePath); filePath = uri.getPath(); } catch (URISyntaxException e) {} // fix encoded file names (for example, with "%20" instead of spaces) try { filePath = URLDecoder.decode(filePath, "UTF-8"); } catch (UnsupportedEncodingException e) {} return filePath; } /** * Method to return the directory path part of a URL (excluding the file name). * For example, the URL "file:/users/strubin/gates.elib" has the directory part "/users/strubin/". * @param url the URL to the file. * @return the directory path part (including the trailing "/", ":", or "\"). * If there is no directory part, returns "". */ public static String getFilePath(URL url) { if (url == null) return ""; String filePath = URLtoString(url); // special case of .delib files, which are directories, but we want them to appear as files File file = new File(filePath); if (file.getName().toLowerCase().endsWith(".delib")) { filePath = file.getPath(); } //if (filePath.toLowerCase().endsWith(".delib"+File.separator)) // filePath = filePath.substring(0, filePath.length()-1); // remove trailing '/' int backSlashPos = filePath.lastIndexOf('\\'); int colonPos = filePath.lastIndexOf(':'); int slashPos = filePath.lastIndexOf('/'); int charPos = Math.max(backSlashPos, Math.max(colonPos, slashPos)); if (charPos < 0) return ""; return filePath.substring(0, charPos+1); } /** * Method to return the pure file name of a URL. * The pure file name excludes the directory path and the extension. * It is used to find the library name from a URL. * For example, the URL "file:/users/strubin/gates.elib" has the pure file name "gates". * @param url the URL to the file. * @return the pure file name. */ public static String getFileNameWithoutExtension(URL url) { return getFileNameWithoutExtension(URLtoString(url)); } /** * Method to return the pure file name of a file path. * The pure file name excludes the directory path and the extension. * It is used to find the library name from a file patj. * For example, the file path "file:/users/strubin/gates.elib" has the pure file name "gates". * @param fileName full name of file. * @return the pure file name. */ public static String getFileNameWithoutExtension(String fileName) { // special case if the library path came from a different computer system and still has separators while (fileName.endsWith("\\") || fileName.endsWith(":") || fileName.endsWith("/")) fileName = fileName.substring(0, fileName.length()-1); int backSlashPos = fileName.lastIndexOf('\\'); int colonPos = fileName.lastIndexOf(':'); int slashPos = fileName.lastIndexOf('/'); int charPos = Math.max(backSlashPos, Math.max(colonPos, slashPos)); if (charPos >= 0) fileName = fileName.substring(charPos+1); int dotPos = fileName.lastIndexOf('.'); if (dotPos >= 0) fileName = fileName.substring(0, dotPos); // make sure the file name is legal StringBuffer buf = null; for (int i = 0; i < fileName.length(); i++) { char ch = fileName.charAt(i); if (ch == '\n' || ch == '|' || ch == ':' || ch == ' ' || ch == '{' || ch == '}' || ch == ';') { if (buf == null) { buf = new StringBuffer(); buf.append(fileName.substring(0, i)); } buf.append('-'); continue; } else if (buf != null) { buf.append(ch); } } if (buf != null) { String newS = buf.toString(); System.out.println("File name " + fileName + " was converted to " + newS); return newS; } return fileName; } /** * Method to return the extension of the file in a URL. * The extension is the part after the last dot. * For example, the URL "file:/users/strubin/gates.elib" has the extension "elib". * @param url the URL to the file. * @return the extension of the file ("" if none). */ public static String getExtension(URL url) { if (url == null) return ""; String fileName = URLtoString(url); int dotPos = fileName.lastIndexOf('.'); if (dotPos < 0) return ""; return fileName.substring(dotPos+1); } /** * Method to open an input stream to a URL. * @param url the URL to the file. * @return the InputStream, or null if the file cannot be found. */ public static InputStream getURLStream(URL url) { return getURLStream(url, null); } /** * Method to open an input stream to a URL. * @param url the URL to the file. * @param errorMsg a string buffer in which to print any error message. If null, * any error message is printed to System.out * @return the InputStream, or null if the file cannot be found. */ public static InputStream getURLStream(URL url, StringBuffer errorMsg) { if (url != null) { try { return url.openStream(); } catch (IOException e) { if (errorMsg != null) errorMsg.append("Error: cannot open " + e.getMessage() + "\n"); else System.out.println("Error: cannot open " + e.getMessage()); } } return null; } /** * Method to tell whether a given URL exists. * @param url the URL in question. * @return true if the file exists. */ public static boolean URLExists(URL url) { return URLExists(url, null); } /** * Method to tell whether a given URL exists. * @param url the URL in question. * @param errorMsg a string buffer in which to print any error message. * If null, errors are not printed. * @return true if the file exists. */ public static boolean URLExists(URL url, StringBuffer errorMsg) { if (url == null) return false; try { URLConnection con = url.openConnection(); con.connect(); int conLength = con.getContentLength(); con.getInputStream().close(); if (conLength < 0) return false; } catch (Exception e) { if (errorMsg != null) errorMsg.append("Error: cannot open " + e.getMessage() + "\n"); return false; } return true; } /** * Method to examine a path and return all resources found there. * @param resourceName the path to examine. * @return a List of all resource names found there. */ public static List<String> getAllResources(String resourceName) { List<String> retval = new ArrayList<String>(); String cp = System.getProperty("java.class.path", "."); String[] cpElements = cp.split(File.pathSeparator); for(String cpElement : cpElements) { String classPath = cpElement + File.separator + resourceName.replace('.', File.separatorChar); File file = new File(classPath); if (file.isDirectory()) { retval.addAll(getResourcesFromDirectory(file)); } else { File jarFile = new File(cpElement); retval.addAll(getResourcesFromJarFile(jarFile, resourceName.replace('.', '/'))); } } return retval; }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -