在大家开发java程序的时候,往往都会用到一些代码段,而这些代码都可以很好的帮助程序员开发程序,那接下来,我们就来给大家分享一些java编程代码。大家可以参考以下。
1.向文件末尾添加内容
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(); } }
2.得到当前方法的名字
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
3. 转字符串到日期
java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);
//或者是:
SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" ); Date date = format.parse( myString );
4.把 Java util.Date 转成 sql.Date
java.util.Date utilDate = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
5. 使用NIO进行快速的文件拷贝
public static void fileCopy(File in , File out) throws IOException { FileChannel inChannel = new FileInputStream( in ) .getChannel(); FileChannel outChannel = new FileOutputStream(out) .getChannel(); try { // inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large files on Windows // magic number for Windows, 64Mb - 32Kb) int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
6.抓屏程序
import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.io.File; ... 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)); } ...
7.把 Array 转换成 Map
import java.util.Map; import org.apache.commons.lang.ArrayUtils; public class Main { public static void main(String[] args) { String[][] countries = { { "United States" , "New York" } , { "United Kingdom" , "London" } , { "Netherland" , "Amsterdam" } , { "Japan" , "Tokyo" } , { "France" , "Paris" } }; Map countryCapitals = ArrayUtils.toMap(countries); System.out.println("Capital of Japan is " + countryCapitals.get("Japan")); System.out.println("Capital of France is " + countryCapitals.get("France")); } }
8.单实例Singleton 示例
public class SimpleSingleton { private static SimpleSingleton singleInstance = new SimpleSingleton(); //Marking default constructor private //to avoid direct instantiation. private SimpleSingleton() {} //Get instance for class SimpleSingleton public static SimpleSingleton getInstance() { return singleInstance; } }
这些都是在实际工作中经常用到的代码,大家可以将这些收藏,方便以后开发程序的时候拿出来使用!最后大家如果想要了解更多java初识知识,敬请关注奇Q工具网。
推荐阅读: