아래는 매우 유용한 20 개의 Java 프로그램 스 니펫입니다. 유용하기를 바랍니다.
1. 문자열에는 정수 변환이 있습니다
문자열 a = string.valueof (2); // 숫자 문자열에 대한 정수 int i = integer.parseint (a); // 숫자 문자열 int
2. 파일 끝에 컨텐츠를 추가하십시오
BufferedWriter out = null; try {out = new BufferedWriter (new filewriter ( "filename", true)); out.write ( "Astring"); } catch (ioException e) {// 오류 처리 코드} 마지막으로 {if (out! = null) {out.close (); }} 3. 현재 방법의 이름을 얻으십시오
String MethodName = thread.currentThread (). getStackTrace () [1] .getMethodName ();
4. 현재까지 문자열을 돌립니다
java.util.date = java.text.dateformat.getDateInstance (). Parse (날짜 문자열); 또는 : simpledateformat format = new simpledateformat ( "dd.mm.yyyy"); 날짜 날짜 = format.parse (mystring);
5. JDBC와 Oracle을 연결하십시오
공개 클래스 oraclejdbctest {String driverclass = "oracle.jdbc.driver.oracledriver"; 연결 사기; public void init (fileInputStream fs)는 classNotFoundException, sqlexception, filenotfoundException, ioException {properties propss = new Properties (); props.load (fs); 문자열 url = propss.getProperty ( "db.url"); 문자열 username = props.getProperty ( "db.user"); 문자열 비밀번호 = props.getProperty ( "db.password"); class.forname (DriverClass); con = drivermanager.getConnection (url, username, password); } public void fetch ()는 sqlexception, ioexception {proadstatement ps = con.preparestatement ( "듀얼에서 sysdate 선택"); resultSet rs = ps.ExecuteQuery (); while (rs.next ()) {// 당신이하는 일을합니다} rs.close (); ps.close (); } public static void main (String [] args) {OracleJdbcTest test = new OracleJdbcTest (); test.init (); test.fetch (); }} 6. Java Util.Date를 SQL.Date로 변환하십시오
java.util.date utildate = new java.util.date (); java.sql.date sqldate = new java.sql.date (utildate.gettime ());
7. 빠른 파일 복사를 위해 NIO를 사용하십시오
public static void filecopy (file in, file out)는 ioexception {filechannel interchannel = new FileInputStream (in) .getChannel (); filechannel outChannel = 새 FileOutputStream (out) .getChannel (); try {// eNCANNEL.TRANSFERTO (0, inticannel.size (), OutChannel); // 원본 - Windows에서 큰 파일을 복사하는 데 어려움이있는 것 // Windows의 Magic Number, 64MB -32KB) int maxcount = (64 * 1024 * 1024) - (32 * 1024); 긴 크기 = inchannel.size (); 긴 위치 = 0; while (position <size) {position += inchannel.transferto (position, maxcount, outChannel); }} 마침내 {if (inchannel! = null) {encannel.close (); } if (outChannel! = null) {outChannel.close (); }}} 8. 이미지의 축소판을 만듭니다
Private void CreateThumbnail (String filename, int tummwidth, int jumbheight, int quality, string outfilename)은 InterruptedException, filenotfoundException, ioexception {// filename image image = toolkit.getDefaultToolkit (). getImage (filename); MediaTracker MediaTracker = New MediaTracker (New Container ()); MediaTracker.AdDimage (image, 0); MediaTracker.waitforid (0); //이 시점에서 오류를 테스트하는 데 이것을 사용하십시오 : System.out.println (mediaTracker.iserRorany ()); // 너비와 높이에서 썸네일 크기를 결정합니다. 더블 덤 브라 티오 = (이중) 썸폭 / (더블) 썸 하이트; int imageWidth = image.getWidth (null); int imageHeight = image.getheight (null); Double ImageRatio = (Double) imageWidth / (Double) ImageHeight; if (thumbratio <imageratio) {thumbheight = (int) (whilwidth / imageratio); } else {thumbwidth = (int) (Thumbheight * imageratio); } // 원본 이미지를 축소판 이미지 객체로 그리거나 // 새 크기로 확장하여 -Fly-BufferedImage ThumbImage = New BufferedImage (Thumbwidth, Thumbheight, BufferedImage.type_int_rgb); Graphics2d Graphics2d = thumbimage.creategraphics (); Graphics2d.SetRenderingHint (renderingHints.Key_InterPolation, renderingHints.Value_InterPolation_Bilinear); Graphics2d.DrawImage (image, 0, 0, ummwidth, thumbheight, null); // 썸네일 이미지를 OutfileName에 저장 BufferedOutputStream out = new BufferedOutputStream (new FileoutPutStream (outfilename)); jpegimageEncoder encoder = jpegcodec.createjpegencoder (out); jpegencodeparam param = encoder.getDefaultJpegencodeparam (ThumbImage); 품질 = math.max (0, math.min (품질, 100)); param.setquality ((float) 품질 / 100.0f, false); encoder.setjpegencodeparam (param); encoder.encode (썸이지); out.close (); }9. JSON 형식 데이터를 만듭니다
그리고 다음 JAR 파일 : JSON-RPC-1.0.jar (75 KB)
import org.json.jsonobject; ... ... jsonobject json = new JsonObject (); JSON.PUT ( "City", "Mumbai"); json.put ( "국가", "인도"); ... 문자열 출력 = json.tostring (); ...
10. itext jar를 사용하여 PDF를 생성합니다
import java.io.file; import java.io.fileoutputStream; import java.io.outputStream; import java.util.date; com.lowagie.text.document import; import com.lowagie.text.paragraph; import com.lowagie.text.pdf.pdfwriter; public class generatepdf {public static void main (String [] args) {try {outputStream file = new FileOutputStream (새 파일 ( "c : //test.pdf")); 문서 문서 = 새 문서 (); pdfwriter.getInstance (문서, 파일); document.open (); document.add (새 단락 ( "Hello Kiran")); document.add (새 단락 (새 날짜 (). toString ()); document.close (); file.close (); } catch (예외 e) {e.printstacktrace (); }}} 11. 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. 단일 인스턴스 싱글 톤 예제
공개 클래스 SIMPLESINGETON {Private STATIC SIMPLESINGLETON SINGINSTANCE = NEW SIMPLESINGLETON (); // 기본 생성자 표시 개인 // 직접 인스턴스화를 피하기 위해. Private SimplesingLeTon () {} // 클래스 SIMPLESINGETON의 인스턴스 가져옵니다. 공개 정적 SimplySingleTon getInstance () {return SingleInstance; }} 또 다른 구현
공개 열거 Simplesingleton {인스턴스; public void dosomething () {}} // 싱글 톤에서 메소드를 호출하십시오 : simplesingleton.instance.dosomething (); 13. 스크린 캡처 프로그램
java.awt.dimension import; import java.awt.rectangle; java.awt.robot import; java.awt.toolkit import; java.awt.image.bufferedimage import; import javax.imageio.imageio; import java.io.file; ... public void capturescreen (String filename)은 예외 {dimension screensize = toolkit.getDefaultToolKit (). getScreensize (); 사각형 ScreenRectangle = 새로운 사각형 (Screensize); 로봇 로봇 = 새로운 로봇 (); BufferedImage image = robot.createscreencapture (screenrecreceange); imageio.write (image, "png", 새 파일 (filename)); } ... 14. 파일과 디렉토리를 나열하십시오
파일 dir = 새 파일 ( "directoryName"); 문자열 [] children = dir.list (); if (children == null) {// dir dir가 존재하지 않거나 디렉토리가 아님} else {for (int i = 0; i <children.length; i ++) {// 파일 또는 디렉토리 filename = children [i]; }} // 반환 된 파일 목록을 필터링 할 수도 있습니다. //이 예제는`. '로 시작하는 파일을 반환하지 않습니다. filenameFilter 필터 = new FilEnameFilter () {public boolean accept (파일, 문자열 이름) {return! name.startSwith ( "."); }}; children = dir.list (필터); // 파일 목록은 파일 개체 파일 [] files = dir.listFiles ()로 검색 될 수 있습니다. //이 필터는 Directies FileFilter FileFilter = New FileFilter () {public boolean accept (파일 파일) {return file.isdirectory (); }}; files = dir.listfiles (filefilter); 15. zip 및 jar 파일을 만듭니다
import java.util.zip.*; java.io.*; public class Zipit {public static void main (String Args [])는 ioexception {if (args.length <2) {System.err.println ( "사용 : Java Zipit Zip.zip file2 file3"); System.exit (-1); } 파일 zipfile = 새 파일 (args [0]); if (zipfile.exists ()) {System.err.println ( "zip 파일이 이미 존재하고 다른 시도를 시도하십시오"); System.exit (-2); } fileoutputStream fos = 새 FileOutputStream (ZipFile); ZipOutputStream ZOS = 새로운 ZipOutputStream (FOS); int bytesread; 바이트 [] 버퍼 = 새로운 바이트 [1024]; CRC32 CRC = 새로운 CRC32 (); for (int i = 1, n = args.length; i <n; i ++) {string name = args [i]; 파일 = 새 파일 (이름); if (! file.exists ()) {system.err.println ( "건너 뛰기 :" + name); 계속하다; } bufferedInputStream bis = new bufferedInputStream (new FileInputStream (file)); crc.reset (); while ((bytesread = bis.read (buffer))! = -1) {crc.update (buffer, 0, bytesread); } bis.close (); // 입력 스트림의 시작으로 재설정 bis = new bufferedInputStream (new FileInputStream (file)); Zipentry Entry = New Zipentry (이름); EntrySetMethod (Zipentry.stored); EntrySetCompressedSize (file.length ()); Entrysetsize (file.length ()); Entry.setcrc (crc.getValue ()); Zos.putNextEntry (Entry); while ((bytesread = bis.read (buffer))! = -1) {zos.write (buffer, 0, bytesread); } bis.close (); } zos.close (); }}16. 구문 분석/읽기 XML 파일
XML 파일
<? XML 버전 = "1.0"?> <tudent> <tudent> <name> John </name> <grade> b </grade> </age> </student> </student> <name> </name> <grade> a </grade> <age> 11 </age> </student> <naint> <name> </student> </grade> <18
자바 코드
패키지 net.viralpatel.java.xmlparser; import java.io.file; import javax.xml.parsers.documentBuilder; import javax.xml.parsers.documentbuilderfactory; import org.w3c.dom.document; import org.w3c.dom.element; import org.w3c.dom.node; import org.w3c.dom.nodelist; public class xmlparser {public void getAllUserNames (String filename) {try {documentBuilDerfactory dbf = documentBuilDerfactory.newinstance (); DocumentBuilder db = dbf.newDocumentBuilder (); 파일 = 새 파일 (filename); if (file.exists ()) {document doc = db.parse (file); 요소 docele = doc.getDocumentElement (); // 문서 System.out.println의 루트 요소 인쇄 ( "문서의 루트 요소 :" + docele.getNodename ()); Nodelist StudentList = docele.getElementsByTagName ( "학생"); // 문서 시스템에서 총 학생 요소를 인쇄합니다. if (StudentList! = null && whitulationlist.getLength ()> 0) {for (int i = 0; i <StudentList.getLength (); i ++) {Node Node = StudentList.Item (i); if (node.getNodetype () == node.element_node) {system.out .println ( "======================="); 요소 e = (요소) 노드; NODELIST NODELIST = E.GetElementsByTagName ( "이름"); System.out.println ( "이름 :" + nodelist.item (0) .getchildnodes (). item (0) .getNodevalue ()); nodelist = e.getElementsByTagName ( "등급"); System.out.println ( "등급 :" + nodelist.item (0) .getchildnodes (). item (0) .getNodevalue ()); nodelist = e.getElementsByTagName ( "Age"); System.out.println ( "age :" + nodelist.item (0) .getchildnodes (). item (0) .getNodevalue ()); }} else {system.exit (1); }}} catch (예외 e) {system.out.println (e); }} public static void main (String [] args) {xmlparser parser = new xmlparser (); parser.getallusernames ( "c : //test.xml"); }} 17. 배열을 맵으로 변환합니다
java.util.map import; import org.apache.commons.lang.arrayutils; 공개 클래스 메인 {public static void main (string [] args) {String [] [] 국가 = {{{{United States ","New York "}, {"영국 ","런던 "},"네덜란드 ","암스테르담 "}, {"일본 ","Tokyo "}, {프랑스", "Paris"}}; MAP CountryCapitals = arrayutils.tomap (국가); System.out.println ( "일본의 수도" + CountryCapitals.get ( "Japan")); System.out.println ( "프랑스의 수도" " + CountryCapitals.get ("France ")); }} 18. 이메일 보내기
javax.mail.*; javax.mail.internet.*import.*; java.util.*; public void postmail (문자열 수신자 [], 문자열 주제, 문자열 메시지, 문자열)는 messagingException {boolean debug = false; // 호스트 SMTP 주소 속성을 설정합니다. propss = new Properties (); props.put ( "mail.smtp.host", "smtp.example.com"); // 일부 속성을 만들고 기본 세션 세션을 가져옵니다. 세션 = 세션 .getDefaultInstance (propss, null); 세션 .SetDeBug (디버그); // 메시지 작성 메시지 MSG = New Mimemessage (세션); // InternetAdDress 주소를 설정하고 주소로 설정하십시오. msg.setfrom (주소); InternetAdDress [] addressTo = new InternetAdDress [수신자.length]; for (int i = 0; i <수신자.length; i ++) {addressto [i] = new InternetAddress (수신자 [i]); } msg.setRecipients (message.recipienttype.to, addressto); // 선택 사항 : msg.addheader ( "myheadername", "myheadervalue")를 원하는 경우 이메일에 사용자 정의 헤더를 설정할 수도 있습니다. // 주제 및 내용 유형 설정 MSG.SETSUBJECT (주제); msg.setContent (메시지, "text/plain"); 운송 .send (MSG); } 19. 데이터 생성에 대한 HTTP 요청을 보냅니다
import java.io.bufferedReader; import java.io.inputStreamReader; import java.net.url; public class main {public static void main (String [] args) {try {url my_url = new URL ( "http://coolshell.cn/"); bufferedReader br = new bufferedReader (new inputStreamReader (my_url.openstream ())); 문자열 strtemp = ""; while (null! = (strtemp = br.readline ())) {system.out.println (strtemp); }} catch (예외 예) {ex.printstacktrace (); }}} 20. 배열의 크기를 변경하십시오
/** * 새 크기의 배열을 재 할당하고 이전 배열의 내용 *을 새 배열에 복사합니다. * @param oldarray 기존 배열은 재 할당됩니다. * @Param은 새로운 배열 크기를 뉴스립니다. * @동일한 내용을 가진 새 배열. */private static 객체 ResizEarray (Object OldArray, int Newsize) {int oldsize = java.lang.reflect.array.getLength (OldArray); 클래스 elementType = oldArray.getClass (). getComponentType (); Object NewArray = java.lang.reflect.array.newinstance (ElementType, Newsize); int preservelength = math.min (Oldsize, Newsize); if (preservelength> 0) System.arrayCopy (OldArray, 0, NewArray, 0, Preservelength); NewArray를 반환하십시오. } // resizearRay ()에 대한 루틴을 테스트합니다. public static void main (String [] args) {int [] a = {1,2,3}; a = (int []) resizearray (a, 5); A [3] = 4; A [4] = 5; for (int i = 0; i <a.length; i ++) system.out.println (a [i]); }이 기사가 모든 사람이 Java 프로그래밍을 배우는 데 도움이되기를 바랍니다.