集合了一些常用的小片段


  1. 1. 字符串有整型的相互转换
  2. Java代码
  3. String a = String.valueOf(2); //integer to numeric string
  4. int i = Integer.parseInt(a); //numeric string to an int
  5. 2. 向文件末尾添加内容
  6. Java代码
  7. BufferedWriter out = null;
  8. try {
  9. out = new BufferedWriter(new FileWriter(”filename”, true));
  10. out.write(”aString”);
  11. } catch (IOException e) {
  12. // error processing code
  13. } finally {
  14. if (out != null) {
  15. out.close();
  16. }
  17. }
  18. Java代码
  19. [size=medium][b]3. 得到当前方法的名字[/b][/size]
  20. String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
  21. 4. 转字符串到日期
  22. Java代码
  23. java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);
  24. 或者是:
  25. Java代码
  26. SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
  27. Date date = format.parse( myString );
  28. 5. 使用JDBC链接Oracle
  29. Java代码
  30. public class OracleJdbcTest
  31. {
  32. String driverClass = "oracle.jdbc.driver.OracleDriver";
  33. Connection con;
  34. public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException
  35. {
  36. Properties props = new Properties();
  37. props.load(fs);
  38. String url = props.getProperty("db.url");
  39. String userName = props.getProperty("db.user");
  40. String password = props.getProperty("db.password");
  41. Class.forName(driverClass);
  42. con=DriverManager.getConnection(url, userName, password);
  43. }
  44. public void fetch() throws SQLException, IOException
  45. {
  46. PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");
  47. ResultSet rs = ps.executeQuery();
  48. while (rs.next())
  49. {
  50. // do the thing you do
  51. }
  52. rs.close();
  53. ps.close();
  54. }
  55. public static void main(String[] args)
  56. {
  57. OracleJdbcTest test = new OracleJdbcTest();
  58. test.init();
  59. test.fetch();
  60. }
  61. }
  62. 6. Java util.Date 转成 sql.Date
  63. Java代码
  64. java.util.Date utilDate = new java.util.Date();
  65. java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
  66. 7. 使用NIO进行快速的文件拷贝
  67. Java代码
  68. public static void fileCopy( File in, File out )
  69. throws IOException
  70. {
  71. FileChannel inChannel = new FileInputStream( in ).getChannel();
  72. FileChannel outChannel = new FileOutputStream( out ).getChannel();
  73. try
  74. {
  75. // inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large files on Windows
  76. // magic number for Windows, 64Mb - 32Kb)
  77. int maxCount = (64 * 1024 * 1024) - (32 * 1024);
  78. long size = inChannel.size();
  79. long position = 0;
  80. while ( position < size )
  81. {
  82. position += inChannel.transferTo( position, maxCount, outChannel );
  83. }
  84. }
  85. finally
  86. {
  87. if ( inChannel != null )
  88. {
  89. inChannel.close();
  90. }
  91. if ( outChannel != null )
  92. {
  93. outChannel.close();
  94. }
  95. }
  96. }
  97. 8. 创建图片的缩略图
  98. Java代码
  99. private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)
  100. throws InterruptedException, FileNotFoundException, IOException
  101. {
  102. // load image from filename
  103. Image image = Toolkit.getDefaultToolkit().getImage(filename);
  104. MediaTracker mediaTracker = new MediaTracker(new Container());
  105. mediaTracker.addImage(image, 0);
  106. mediaTracker.waitForID(0);
  107. // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());
  108. // determine thumbnail size from WIDTH and HEIGHT
  109. double thumbRatio = (double)thumbWidth / (double)thumbHeight;
  110. int imageWidth = image.getWidth(null);
  111. int imageHeight = image.getHeight(null);
  112. double imageRatio = (double)imageWidth / (double)imageHeight;
  113. if (thumbRatio < imageRatio) {
  114. thumbHeight = (int)(thumbWidth / imageRatio);
  115. } else {
  116. thumbWidth = (int)(thumbHeight * imageRatio);
  117. }
  118. // draw original image to thumbnail image object and
  119. // scale it to the new size on-the-fly
  120. BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
  121. Graphics2D graphics2D = thumbImage.createGraphics();
  122. graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  123. graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
  124. // save thumbnail image to outFilename
  125. BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
  126. JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  127. JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
  128. quality = Math.max(0, Math.min(quality, 100));
  129. param.setQuality((float)quality / 100.0f, false);
  130. encoder.setJPEGEncodeParam(param);
  131. encoder.encode(thumbImage);
  132. out.close();
  133. }
  134. 9. 创建 JSON 格式的数据
  135. 请先阅读这篇文章 了解一些细节,
  136. 并下面这个JAR 文件:json-rpc-1.0.jar (75 kb)
  137. Java代码
  138. import org.json.JSONObject;
  139. ...
  140. ...
  141. JSONObject json = new JSONObject();
  142. json.put("city", "Mumbai");
  143. json.put("country", "India");
  144. ...
  145. String output = json.toString();
  146. ...
  147. 10. 使用iText JAR生成PDF
  148. 阅读这篇文章 了解更多细节
  149. Java代码
  150. import java.io.File;
  151. import java.io.FileOutputStream;
  152. import java.io.OutputStream;
  153. import java.util.Date;
  154. import com.lowagie.text.Document;
  155. import com.lowagie.text.Paragraph;
  156. import com.lowagie.text.pdf.PdfWriter;
  157. public class GeneratePDF {
  158. public static void main(String[] args) {
  159. try {
  160. OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
  161. Document document = new Document();
  162. PdfWriter.getInstance(document, file);
  163. document.open();
  164. document.add(new Paragraph("Hello Kiran"));
  165. document.add(new Paragraph(new Date().toString()));
  166. document.close();
  167. file.close();
  168. } catch (Exception e) {
  169. e.printStackTrace();
  170. }
  171. }
  172. }
  173. 11. HTTP 代理设置
  174. 阅读这篇 文章 了解更多细节。
  175. Java代码
  176. System.getProperties().put("http.proxyHost", "someProxyURL");
  177. System.getProperties().put("http.proxyPort", "someProxyPort");
  178. System.getProperties().put("http.proxyUser", "someUserName");
  179. System.getProperties().put("http.proxyPassword", "somePassword");
  180. 12. 单实例Singleton 示例
  181. 请先阅读这篇文章 了解更多信息
  182. Java代码
  183. public class SimpleSingleton {
  184. private static SimpleSingleton singleInstance = new SimpleSingleton();
  185. //Marking default constructor private
  186. //to avoid direct instantiation.
  187. private SimpleSingleton() {
  188. }
  189. //Get instance for class SimpleSingleton
  190. public static SimpleSingleton getInstance() {
  191. return singleInstance;
  192. }
  193. }
  194. 另一种实现
  195. Java代码
  196. public enum SimpleSingleton {
  197. INSTANCE;
  198. public void doSomething() {
  199. }
  200. }
  201. //Call the method from Singleton:
  202. SimpleSingleton.INSTANCE.doSomething();
  203. 13. 抓屏程序
  204. 阅读这篇文章 获得更多信息。
  205. Java代码
  206. import java.awt.Dimension;
  207. import java.awt.Rectangle;
  208. import java.awt.Robot;
  209. import java.awt.Toolkit;
  210. import java.awt.image.BufferedImage;
  211. import javax.imageio.ImageIO;
  212. import java.io.File;
  213. ...
  214. public void captureScreen(String fileName) throws Exception {
  215. Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
  216. Rectangle screenRectangle = new Rectangle(screenSize);
  217. Robot robot = new Robot();
  218. BufferedImage image = robot.createScreenCapture(screenRectangle);
  219. ImageIO.write(image, "png", new File(fileName));
  220. }
  221. ...
  222. 14. 列出文件和目录
  223. Java代码
  224. File dir = new File("directoryName");
  225. String[] children = dir.list();
  226. if (children == null) {
  227. // Either dir does not exist or is not a directory
  228. } else {
  229. for (int i=0; i < children.length; i++) {
  230. // Get filename of file or directory
  231. String filename = children[i];
  232. }
  233. }
  234. // It is also possible to filter the list of returned files.
  235. // This example does not return any files that start with `.'.
  236. FilenameFilter filter = new FilenameFilter() {
  237. public boolean accept(File dir, String name) {
  238. return !name.startsWith(".");
  239. }
  240. };
  241. children = dir.list(filter);
  242. // The list of files can also be retrieved as File objects
  243. File[] files = dir.listFiles();
  244. // This filter only returns directories
  245. FileFilter fileFilter = new FileFilter() {
  246. public boolean accept(File file) {
  247. return file.isDirectory();
  248. }
  249. };
  250. files = dir.listFiles(fileFilter);
  251. 15. 创建ZIPJAR文件
  252. Java代码
  253. import java.util.zip.*;
  254. import java.io.*;
  255. public class ZipIt {
  256. public static void main(String args[]) throws IOException {
  257. if (args.length < 2) {
  258. System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");
  259. System.exit(-1);
  260. }
  261. File zipFile = new File(args[0]);
  262. if (zipFile.exists()) {
  263. System.err.println("Zip file already exists, please try another");
  264. System.exit(-2);
  265. }
  266. FileOutputStream fos = new FileOutputStream(zipFile);
  267. ZipOutputStream zos = new ZipOutputStream(fos);
  268. int bytesRead;
  269. byte[] buffer = new byte[1024];
  270. CRC32 crc = new CRC32();
  271. for (int i=1, n=args.length; i < n; i++) {
  272. String name = args[i];
  273. File file = new File(name);
  274. if (!file.exists()) {
  275. System.err.println("Skipping: " + name);
  276. continue;
  277. }
  278. BufferedInputStream bis = new BufferedInputStream(
  279. new FileInputStream(file));
  280. crc.reset();
  281. while ((bytesRead = bis.read(buffer)) != -1) {
  282. crc.update(buffer, 0, bytesRead);
  283. }
  284. bis.close();
  285. // Reset to beginning of input stream
  286. bis = new BufferedInputStream(
  287. new FileInputStream(file));
  288. ZipEntry entry = new ZipEntry(name);
  289. entry.setMethod(ZipEntry.STORED);
  290. entry.setCompressedSize(file.length());
  291. entry.setSize(file.length());
  292. entry.setCrc(crc.getValue());
  293. zos.putNextEntry(entry);
  294. while ((bytesRead = bis.read(buffer)) != -1) {
  295. zos.write(buffer, 0, bytesRead);
  296. }
  297. bis.close();
  298. }
  299. zos.close();
  300. }
  301. }
  302. 16. 解析/读取XML 文件
  303. XML文件
  304. 代码
  305. <?xml version="1.0"?>
  306. <students>
  307. <student>
  308. <name>John</name>
  309. <grade>B</grade>
  310. <age>12</age>
  311. </student>
  312. <student>
  313. <name>Mary</name>
  314. <grade>A</grade>
  315. <age>11</age>
  316. </student>
  317. <student>
  318. <name>Simon</name>
  319. <grade>A</grade>
  320. <age>18</age>
  321. </student>
  322. </students>
  323. Java代码
  324. package net.viralpatel.java.xmlparser;
  325. import java.io.File;
  326. import javax.xml.parsers.DocumentBuilder;
  327. import javax.xml.parsers.DocumentBuilderFactory;
  328. import org.w3c.dom.Document;
  329. import org.w3c.dom.Element;
  330. import org.w3c.dom.Node;
  331. import org.w3c.dom.NodeList;
  332. public class XMLParser {
  333. public void getAllUserNames(String fileName) {
  334. try {
  335. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  336. DocumentBuilder db = dbf.newDocumentBuilder();
  337. File file = new File(fileName);
  338. if (file.exists()) {
  339. Document doc = db.parse(file);
  340. Element docEle = doc.getDocumentElement();
  341. // Print root element of the document
  342. System.out.println("Root element of the document: "
  343. + docEle.getNodeName());
  344. NodeList studentList = docEle.getElementsByTagName("student");
  345. // Print total student elements in document
  346. System.out
  347. .println("Total students: " + studentList.getLength());
  348. if (studentList != null && studentList.getLength() > 0) {
  349. for (int i = 0; i < studentList.getLength(); i++) {
  350. Node node = studentList.item(i);
  351. if (node.getNodeType() == Node.ELEMENT_NODE) {
  352. System.out
  353. .println("=====================");
  354. Element e = (Element) node;
  355. NodeList nodeList = e.getElementsByTagName("name");
  356. System.out.println("Name: "
  357. + nodeList.item(0).getChildNodes().item(0)
  358. .getNodeValue());
  359. nodeList = e.getElementsByTagName("grade");
  360. System.out.println("Grade: "
  361. + nodeList.item(0).getChildNodes().item(0)
  362. .getNodeValue());
  363. nodeList = e.getElementsByTagName("age");
  364. System.out.println("Age: "
  365. + nodeList.item(0).getChildNodes().item(0)
  366. .getNodeValue());
  367. }
  368. }
  369. } else {
  370. System.exit(1);
  371. }
  372. }
  373. } catch (Exception e) {
  374. System.out.println(e);
  375. }
  376. }
  377. public static void main(String[] args) {
  378. XMLParser parser = new XMLParser();
  379. parser.getAllUserNames("c:\\test.xml");
  380. }
  381. }
  382. 17. Array 转换成 Map
  383. Java代码
  384. import java.util.Map;
  385. import org.apache.commons.lang.ArrayUtils;
  386. public class Main {
  387. public static void main(String[] args) {
  388. String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" },
  389. { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };
  390. Map countryCapitals = ArrayUtils.toMap(countries);
  391. System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));
  392. System.out.println("Capital of France is " + countryCapitals.get("France"));
  393. }
  394. }
  395. 18. 发送邮件
  396. Java代码
  397. import javax.mail.*;
  398. import javax.mail.internet.*;
  399. import java.util.*;
  400. public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
  401. {
  402. boolean debug = false;
  403. //Set the host smtp address
  404. Properties props = new Properties();
  405. props.put("mail.smtp.host", "smtp.example.com");
  406. // create some properties and get the default Session
  407. Session session = Session.getDefaultInstance(props, null);
  408. session.setDebug(debug);
  409. // create a message
  410. Message msg = new MimeMessage(session);
  411. // set the from and to address
  412. InternetAddress addressFrom = new InternetAddress(from);
  413. msg.setFrom(addressFrom);
  414. InternetAddress[] addressTo = new InternetAddress[recipients.length];
  415. for (int i = 0; i < recipients.length; i++)
  416. {
  417. addressTo[i] = new InternetAddress(recipients[i]);
  418. }
  419. msg.setRecipients(Message.RecipientType.TO, addressTo);
  420. // Optional : You can also set your custom headers in the Email if you Want
  421. msg.addHeader("MyHeaderName", "myHeaderValue");
  422. // Setting the Subject and Content Type
  423. msg.setSubject(subject);
  424. msg.setContent(message, "text/plain");
  425. Transport.send(msg);
  426. }
  427. 19. 发送代数据的HTTP 请求
  428. Java代码
  429. import java.io.BufferedReader;
  430. import java.io.InputStreamReader;
  431. import java.net.URL;
  432. public class Main {
  433. public static void main(String[] args) {
  434. try {
  435. URL my_url = new URL("http://coolshell.cn/");
  436. BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));
  437. String strTemp = "";
  438. while(null != (strTemp = br.readLine())){
  439. System.out.println(strTemp);
  440. }
  441. } catch (Exception ex) {
  442. ex.printStackTrace();
  443. }
  444. }
  445. }
  446. 20. 改变数组的大小
  447. Java代码
  448. /**
  449. * Reallocates an array with a new size, and copies the contents
  450. * of the old array to the new array.
  451. * @param oldArray the old array, to be reallocated.
  452. * @param newSize the new array size.
  453. * @return A new array with the same contents.
  454. */
  455. private static Object resizeArray (Object oldArray, int newSize) {
  456. int oldSize = java.lang.reflect.Array.getLength(oldArray);
  457. Class elementType = oldArray.getClass().getComponentType();
  458. Object newArray = java.lang.reflect.Array.newInstance(
  459. elementType,newSize);
  460. int preserveLength = Math.min(oldSize,newSize);
  461. if (preserveLength > 0)
  462. System.arraycopy (oldArray,0,newArray,0,preserveLength);
  463. return newArray;
  464. }
  465. // Test routine for resizeArray().
  466. public static void main (String[] args) {
  467. int[] a = {1,2,3};
  468. a = (int[])resizeArray(a,5);
  469. a[3] = 4;
  470. a[4] = 5;
  471. for (int i=0; i<a.length; i++)
  472. System.out.println (a[i]);
  473. }

java项目小手册的更多相关文章

  1. 使用 Gradle 构建 Java 项目

    使用 Gradle 构建 Java 项目 这个手册将通过一个简单的 Java 项目向大家介绍如何使用 Gradle 构建 Java 项目. 我们将要做什么? 我们将在这篇文档航中创建一个简单的 Jav ...

  2. Java开发小技巧(三):Maven多工程依赖项目

    前言 本篇文章基于Java开发小技巧(二):自定义Maven依赖中创建的父工程project-monitor实现,运用我们自定义的依赖包进行多工程依赖项目的开发. 下面以多可执行Jar包项目的开发为例 ...

  3. 有了这个开源 Java 项目,开发出炫酷的小游戏好像不难?

    本文适合有 Java 基础知识的人群,跟着本文可学习和运行 Java 的游戏. 本文作者:HelloGitHub-秦人 HelloGitHub 推出的<讲解开源项目>系列,今天给大家带来一 ...

  4. JAVA项目如何打开,打开乱码怎么办,字体太小怎么办,感叹号是什么情况

    打开java项目 Finish 汉字乱码改这里 字体大小改在第一个的 Appearance里面 项目前面有感叹号,都是tomcat和jdk配置有问题

  5. 下载eclipse 配置eclipse 新建Java项目 写一个小程序 运行

    为了更好的学习java,我打算下载个eclipse 地址:https://www.eclipse.org/downloads/packages/ 我们需要下载的版本是Eclipse IDE for J ...

  6. java web项目导入到eclipse中变成了java项目的一种情况的解决办法

    前提,我把代码上传到github上之后,在另外一台电脑上拉下之后,先报出现的是jre不对,然后换成了当前的jre,然后红色的感叹号消失了但是之前项目上那个小地球不见了,也就是说变成了java项目. - ...

  7. Eclipse将引用了第三方jar包的Java项目打包成jar文件的两种方法

    方案一:用Eclipse自带的Export功能 步骤1:准备主清单文件 “MANIFEST.MF”, 由于是打包引用了第三方jar包的Java项目,故需要自定义配置文件MANIFEST.MF,在该项目 ...

  8. XMLHttp小手册,原生ajax参考手册

    个人做java ee开发,在一般的公司里上班,做的是一般的网站. 1.如果经常使用jquery等框架进行异步调用,最主要的不是了解jquery怎么用,而是了解http协议. 2.为了了解http协议, ...

  9. 把我的Java项目部署到Linux系统

    以前,还未毕业,凭借自己三脚猫的功夫,只会在Windows环境中使用tomcat容器把项目跑起来. 以前的操作是,利用Eclipse把项目导出成War包,放到tomcat的webApp文件夹中,鼠标点 ...

随机推荐

  1. 上海第三产业增加值 占比GDP首破七成

    上海第三产业增加值 占比GDP首破七成 2016年08月16日08:10  来源:新闻晨报 分享到:     不久前结束的ChinaJoy上,一家名为HYPEREAL的VR公司展台前,体验者的热情程度 ...

  2. 通过数据库中的表,使用 MyEclipse2017的反向生成工具-->hibernate反转引擎引擎(MyEclipse2017自带的插件) 来反转生成实体类和对应的映射文件

    通过数据库中的表,使用 MyEclipse2017的反向生成工具-->hibernate反转引擎引擎(MyEclipse2017自带的插件) 来反转生成实体类和对应的映射文件   文章目录 Ja ...

  3. 并查集 (poj 1611 The Suspects)

    原题链接:http://poj.org/problem?id=1611 简单记录下并查集的模板 #include <cstdio> #include <iostream> #i ...

  4. PAT甲级——A1082 Read Number in Chinese

    Given an integer with no more than 9 digits, you are supposed to read it in the traditional Chinese ...

  5. Everything-启用http服务器(公网IP)会导致共享文件被搜索引擎搜索

    1. 漏洞利用成功的前提 公网ip 启用http服务器 2.产生原因 启用http服务器功能点:让用户在本地或局域网上的其他电脑使用浏览器进行搜索,并支持文件下载.若拥有公网IP的用户启用此功能,就是 ...

  6. java调js基础

    public static void main(String[] args)throws Exception { ScriptEngine se = new ScriptEngineManager() ...

  7. ES6之字符串学习

    以下是常用的方法不是全部方法 1.codePointAt()方法 有一些字段需要4个字节储存,这样charCodeAt方法的返回就是不正确的,用codePointAt()方法就可以返回 十进制的值.如 ...

  8. [转]C#委托的异步调用

    本文将主要通过“同步调用”.“异步调用”.“异步回调”三个示例来讲解在用委托执行同一个“加法类”的时候的的区别和利弊. 首先,通过代码定义一个委托和下面三个示例将要调用的方法: ); //模拟该方法运 ...

  9. HZOI20190829模拟33题解

    题面:https://www.cnblogs.com/Juve/articles/11436771.html A:春思 我们对a分解质因数,则$a=\prod\limits_p^{p|a}p^k$ 所 ...

  10. css的书写位置+元素分类

    1.css的书写位置 1>行内样式: <span style="color:red;">haha</span> 2>内部样式 在style标签中 ...