标题: (整理and分享)20个JAVA人员非常有用的功能代码 第一部分 [打印本页] 作者: xbs783 时间: 2016-11-3 18:20 标题: (整理and分享)20个JAVA人员非常有用的功能代码 第一部分 本文将为大家介绍20人员非常有用的Java功能代码。这20段代码,可以成为大家在今后的开发过程中,Java编程手册的重要部分。
由于字数限制,我分两部分上传给大家!
1. 把Strings转换成int和把int转换成String
String a = String.valueOf(2); //integer to numeric string
int i = Integer.parseInt(a); //numeric string to an int
复制代码
2. 向Java文件中添加文本
Updated: Thanks Simone for pointing to exception. I have
changed the code.
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(”filename”, true));
out.write(”aString”);
} catch (IOException e) {
// error processing code
} finally {
if (out != null) {
out.close();
}
}
复制代码
3. 获取Java现在正调用的方法名
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName ();
复制代码
4. 在Java中将String型转换成Date型
java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);
or
SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
Date date = format.parse( myString );
复制代码
5. 通过Java JDBC链接Oracle数据库
public class OracleJdbcTest
{
String driverClass = "oracle.jdbc.driver.OracleDriver";
Connection con;
public void init(FileInputStream fs) throws ClassNotFoundException,
e.printStackTrace();
}
}
}
复制代码
11. 在Java上的HTTP代理设置
System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");
复制代码
12. Java Singleton 例子
Read this article for more
details.
Update: Thanks Markus for the comment. I have updated the code and
changed it to
more robust implementation.
public class SimpleSingleton {
private static SimpleSingleton singleInstance = new SimpleSingleton();
public void captureScreen(String fileName) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize ();
Rectangle screenRectangle = new Rectangle (screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
}
...
复制代码
14. 在Java中的文件,目录列表
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i < children.length; i++) {
// Get filename of file or directory
String filename = children;
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return ! name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles (fileFilter);
复制代码