Java笔记 生成.exe方法 准备manifest.mf
Manifest-Version:1.0
1 jar cvfm *.jar manifest.mf 目录名称
安装exe4j
Project type选”JAR in EXE” mode
Application info 文件名、.exe导出位置
Executable info 选 GUI程序、控制台晨雾、web服务 exe文件名、图标 是否允许多开 32-bit or 64-bit中勾上 Manifest options中DPI选Always
Java invocation右侧+添加Archive选择.jar包 右下角…添加主类
JRE 最低最高 最低选1.7 表中3个删掉,添加自己的jre
Splash screen启动画面
Messages默认英语 没汉语
另一种:Launch4j
注解
包管理 1 2 3 4 5 package a.b.c;import a.b.c.MainClass;import a.b.c.*;
基本结构 1 2 3 4 5 6 7 8 9 10 11 public class ...{ public static void main (String[] args) { ... return ; }; public static void test (String... args) { for (String arg:args){ ... }; }; };
数据类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 byte short int long float double char boolean instanceof 123 0123 0x123 0b0000_0011 System.out.print("..." +...) System.out.println("..." +...) Integer.toBinaryString() Integer.toOctalString() Integer.toHexString() Byte.SIZE Byte.MIN_VALUE Byte.MAX_VALUE Short.SIZE Short.MIN_VALUE Short.MAX_VALUE Long.SIZE Long.MIN_VALUE Long.MAX_VALUE Float.SIZE Float.MIN_VALUE Float.MAX_VALUE Float.SIZE Float.MIN_VALUE Float.MAX_VALUE
读入 1 2 3 4 import java.util.Scanner;int number;Scanner scanner=new Scanner (System.in); number=scanner.nextInt();
字符串 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 String str=new String ("..." ); str=String.valueOf(1 ); str=String.valueOf(Boolean.TRUE); String str=new String (char [],a,b); String str=String.valueOf(char [],a,b); String str="a" ; str=str.concat("b" ); str.length() str.charAt(...) str.indexOf((int )' ' )或str.indexOf(" " ) str.indexOf((int )' ' ,fromIndex)或str.indexOf(" " ,fromIndex) str.lastIndexOf() str=str.replace(a,b) str=str.replaceAll(a,b) str=str.replaceFirst() str=str.substring(beginIndex) str=str.substring(begin,end) String[] strArray=str.split("" ,k) boolean str.startsWith("..." )boolean str.startsWith("..." ,toffset) boolean str.endsWith("..." )str=str.trim(); str=str.toLowerCase(); str=str.toUpperCase(); char [] cs=str.toCharArrary();boolean str1.equals(str2)boolean str1.equalsIgnoreCase(str2)
数据格式化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 System.out.println(String.format("..." ,...)); ("%+d" ,25 ) ("%-5d" ,10 ) ("%04d" ,99 ) ("%,f" ,9999.99 ) ("%(f" ,-99.99 ) ("%#x" 或"%#o" ,99 ) ("%f和%<3.2f" ,99.99 ) ("%1$d,%2$s" ,99 ,"abc" )
日期格式化 1 2 3 4 5 6 7 8 9 10 11 Date date=new Date (); System.out.println(String.format("%tY %tB %td %tH %tM %tS" ,date,date,date,date,date,date));
转化 1 2 3 4 5 boolean str.contains("..." )int str1.compareTo(str2) int str1.compareToIgnoreCase() ? str.hashCode() str=str.toString;
ArrayList 1 2 3 4 5 import java.util.ArrayList;import java.util.List;List<String>strList=new ArrayList <>(); strList.add("..." ); System.out.println(strList.toString());
StringBuilder 1 2 3 4 5 6 7 8 9 10 11 12 13 StringBuilder stringBuilder1=new StringBuilder (); StringBuilder stringBuilder2=new StringBuilder (capacity); StringBuilder stringBuilder3=new StringBuilder ("..." ); StringBuilder stringBuilder4=new StringBuilder (stringBuilder3); stringBuilder.append("..." 或boolean 或'...' 或int 或float 或StringBuilder); System.out.println(stringBuilder); stringBuilder.insert(0 ,...); stringBuilder.delete(begin,end); char stringBuilder.charAt(0 );int stringBuilder.capacity();stringBuilder.replace(start,end,"..." ); stringBuilder.reverse(); System.out.println(stringBuilder.toString());
StringBuffer
Arrays 1 2 3 4 5 6 7 8 9 10 11 12 import java.util.Arrays;char charArray[]=new char []{'a' ,'b' ,'c' ,'d' };String Arrays.toString(charArray) char charArray[][]=new char [][]{{'a' ,'b' ,'c' ,'d' },{'e' ,'f' ,'g' }};String Arrays.deepToString(char Array) int array.lengthArrays.fill(array,123 ); Arrays.fill(array,start,end,123 ); int Arrays.binarySearch(array,value) Arrays.sort(array); char [] copyArray=Arrays.copyOf(charArray,len) boolean Arrays.equals(charArray1,charArray2)
正则表达式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 import java.util.regex.*;String Pattern.matches(String regex,String str) Pattern pattern=Pattern.compile(regex); Matcher matcher=pattern.matcher(str); int groupCount=matcher.groupCount();if (matcher.find()){ for (int i=0 ;i<=groupCount;i++){ System.out.println(matcher.group(i)); }; };
OOP 1 2 3 4 5 6 7 8 9 10 11 12 boolean object1.equals(object2)final static { }; public class ChildClass extends ParentClass { }; super super () super (...)abstract @Override
1 2 3 4 5 6 7 8 9 public interface AnimalService { public void sleep () ; }; public class AnimalServiceImpl implements AnimalService { @Override public void sleep () { }; };
箱操作 1 2 3 4 5 6 7 8 9 10 11 12 Integer x=new Integer (10 或"10" ); Integer y=10 ; int m=x.intValue();int n=x; Integer i1=100 ,i2=100 ; System.out.println(i1==i2); System.out.println(i1.equals(i2)); i1=i2=200 ; System.out.println(i1==i2); System.out.println(i1.equals(i2));
类型常量 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 Integer.SIZE Integer.MIN_VALUE Integer.MAX_VALUE Integer.BYTES Integer.TYPE boolean Integer.equals(Object)static int Integer.compare(int ,int )int Integer.compareTo(Integer)static Integer Integer.valueOf(int )static int Integer.parseInt(String)static Integer Integer.valueOf(String)String Integer.toString() static String Integer.toString(int )static String Integer.toBinaryString(int )static String Integer.toOctalString(int )static String Integer.toHexString(int )static int Integer.signum(int )byte Integer.byteValue()short Integer.shortValue()int Integer.intValue()long Integer.longValue()float Integer.floatValue()double Integer.doubleValue()static int max (int ,int ) static int min (int ,int ) static int sum (int ,int ) Double.MAX_EXPONENT Double.MIN_EXPONENT Double.NEGATIVE_INFINITY Double.POSITIVE_INFINITY Double.NaN Double d=new Double (10.01 或"10.01" ) boolean Double.isNaN()boolean Double.isInfinite() Boolean.TRUE Boolean.FALSE Boolean b=new Boolean (true 或"true" ) boolean logicalAnd (boolean ,boolean ) boolean logicalOr (boolean ,boolean ) boolean logicalXor (boolean ,boolean ) Character.PRIVATE_USE static bool Character.isLowerCase(char )static bool Character.isUpperCase(char )static bool Character.isWhitespace(char )static bool Character.toLowerCase(char )static bool Character.toUpperCase(char )import java.math.BigInteger;import java.math.BigDecimal; BigInteger bigInteger=new BigInteger ("1010" ); System.out.println(bigInteger.toString()); bigInteger=bigInteger.add(new BigInteger ("101" )); BigDecimal bigDecimal=new BigDecimal ("3.14" ); System.out.println(bigDecimal.precision());
数学 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Math.PI Math.E double sin (double ) double atan2 (double ,double ) import java.lang.Math; double ceil (double ) int round (float ) long round (double ) double exp (double ) double pow (double ,double ) int /long /float /double max/min( , )int /long /float /double abs ( ) double nextUp/nextDown( )double Math.random()import java.util.Random; Random ran=new Random (无或seedValue); ran.nextInt() ran.nextInt(int n) ran.nextLong() ran.nextBoolean() ran.nextFloat() ran.nextDouble() ran.nextGaussian()
Enum 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public enum ColorEnum { RED("红色" ),GREEN("绿色" ),YELLOW("黄色" ),BLUE("蓝色" ); public String color; private ColorEnum () {}; private ColorEnum (String color) { this .color=color; }; }; public class UseEnum { public static void main (String[] args) { ColorEnum colorArray[]=ColorEnum.values(); for (int i=0 ;i<colorArray.length;i++){ System.out.println(colorArray[i]); }; for (int i=0 ;i<colorArray.length;i++){ System.out.println(colorArray[i].color); }; System.out.println(ColorEnum.RED.compareTo(ColorEnum.GREEN)); for (int i=0 ;i<colorArray.length;i++){ System.out.println(colorArray[i].ordinal()); }; return ; }; };
EnumSet 挖坑待填
EnumMap 挖坑待填
泛型类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 public class Demo <T>{ private T name; private List<T> desc; public void setName (T name) { this .name=name; return ; }; public T getName () { return name; }; public void setDesc (List<T>desc) { this .desc=desc; return ; }; public List<T>getDesc(){ return desc; }; }; public class Demo <T,S,U>{ private T name; private List<S>desc; private U age; }; public class ...{ public <T> void toString (T t) { System.out.println(t.getClass().getName()); }; public static void main (String[] args) { }; };
Collection接口 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;public class UseCollection { public static void main (String[] args) { Collection<String>collection=new ArrayList <String>(); collection.add("a" ); collection.add("b" ); Iterator iterator=collection.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); }; return ; }; };
List集合 AbstractList Stack Vector AttributeList挖坑待填
ArrayList类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 import java.util.*;public class UseArrayList { public static void main (String[]args) { List<String>list=new ArrayList <String>(); list.add("a" ); list.add("b" ); list.add("c" ); list.remove(1 ); for (String element:list){ System.out.println(element); }; Iterator<String>iterator=list.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); }; return ; }; };
LinkedList类
Set集合 AbstractSet EnumSet LinkedHashSet挖坑待填
HashSet类 1 2 3 4 5 6 import java.util.*;Set<String>hashSet=new HashSet <>(); hashSet.add("..." ); hashSet.remove("..." ); int hashSet.size()Iterator<String>iterator=hashSet.iterator();
TreeSet类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 import java.util.*;public class UseTreeSetMethod { public static void main (String[]args) { TreeSet<Integer>treeSet=new TreeSet <>(); treeSet.add(1 ); treeSet.add(2 ); treeSet.add(3 ); Iterator<Integer>iterator=treeSet.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); }; TreeSet<Person>personSet=new TreeSet <>(); personSet.add(new Person (26 ,"a" )); personSet.add(new Person (22 ,"b" )); personSet.add(new Person (33 ,"c" )); Iterator<Person>personIterator=personSet.iterator(); while (personIterator.hasNext()){ Person person=personIterator.next(); System.out.println("" +person.name+person.age); }; return ; }; }; public class Person implements Comparable <Person>{ public Person (int age,String name) { this .age=age; this .name=name; }; int age; String name; public int compareTo (Person person) { int num=this .age-person.age; return num; }; public String toString () { return "" +this .name+this .age; }; };
Map集合 hashMap 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 public class UseHashMap { public static void main (String[]args) { Map<String,String>hashMap=new HashMap <>(); hashMap.put("a" ,"1" ); hashMap.put("b" ,"2" ); hasMap.put("c" ,"3" ); for (String key:hashMap.keySet()){ System.out.println("" +key+hashMap.get(key)); }; Iterator<Map.Entry<String,String>>it=hashMap.entrySet().iterator(); while (it.hasNext()){ Map.Entry<String,String>entry=it.next(); System.out.println("" +entry.getKey()+entry.getValue()); }; for (Map.Entry<String,String>entry:hasMap.entrySet()){ System.out.println("" +entry.getKey()+entry.getValue()); }; for (String v:hashMap.values()){ System.out.println(v); }; return ; }; };
TreeMap 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import java.util.Iterator;import java.util.TreeMap;public class UseTreeMap { public static void main (String[]args) { TreeMap<Person,String>treeMap=new TreeMap <>(); treeMap.put(new Person (1 ,"a" ),"a1" ); treeMap.put(new Person (2 ,"b" ),"b1" ); treeMap.put(new Person (3 ,"c" ),"c1" ); Iterator<Person>personIterator=treeMap.keySet().iterator(); while (personiterator.hasNext()){ Person person=personIterator.next(); System.out.println(person.toString); }; return ; }; };
Collection算法 1 2 3 Collections.sort(list) Collections.shuffle(list) Collections.reverse(list)
Java反射 获取Class对象的引用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package com.demo;class Student {};public class Test { public static void main (String[]args) { Student student=new Student (); Class clazz=student.getClass(); Class clazz Student.class; try { Class clazz=Class.forName("com.demo.Student" ); }; catch (ClassNotFoundException e){ e.printStackTrace(); }; return ; }; };
获取构造方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 package com.demo;import java.lang.reflect.Constructor;public class Test { public static void main (String[]args) throws Exception{ Class clazz=Class.forName("com.demo.Person" ); Constructor[]constructors=clazz.getDeclaredConstructors(); for (Constructor constructor:constructors){ System.out.println("" +constructor); }; Constructor constructor1=clazz.getConstructor(); Object object1=constructor1.newInstance(); Person person1=(Person)object1; person1.say(); Constructor contructor2=clazz.getConstructor(String.class,int .class) Object object2=constructor2.newInstance("b" ,2 ); Person person2=(Person)object2; person2.say(); return ; }; }; class Person { private String name="a" ; private int age=1 ; public Person () {}; public Person (String name,int age) { this .name=name; this .age=age; }; public void say () { System.out.println("" +name+age); return ; }; };
获取成员变量 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 package com.demo;import java.lang.reflect.Field;public class Test { public static void main (String[]args) { printClassVariables(new Person ()); return ; }; public static void printClassVariables (Object obj) { Class c=obj.getClass(); Field[]fields=c.getDeclaredFields(); for (Field field:fields){ Class fieldType=field.getType(); String typeName=fieldType.getSimpleName(); String fieldName=field.getName(); System.out.println("" +typeName+fieldName); }; return ; }; }; class Person { private String name="a" ; private int age=1 ; };
获取方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 import java.lang.reflect.Method;public class Test { public static void main (String[]args) { printClassMethods(new Person ("a" ,1 )); return ; }; public static void printClassMethods (Object obj) { Class c=obj.getClass(); Method[]methods=c.getDeclareMethods(); for (Method method:methods){ Class returnType=method.getReturnType(); System.out.print(returnType.getSimpleName()); System.out.print("" +method.getName()+"(" ); Class[]parameterTypes=method.getParameterTypes(); for (Class paramType:parameterTypes){ System.out.print(paramType.getSimpleName()+"," ); }; }; return ; }; }; class Person { private String name; private int age; public Person (String name,int age) { this .name=name; this .age=age; }; public void say (String message) { ... return ; }; public void run () { ... return ; }; public void swim () { ... return ; }; };
invoke()调用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 package com.demo;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class Test { public static void main (String[]args) throws InvocationTargetException,IllegalAccessException{ PrintUtil printUtil=new PrintUtil (); Class clazz=printUtil.getClass(); try { Method m1=clazz.getMethod("print" ,int .class,int .class); m1.invoke(printUtil,1 ,2 ); Method m2=clazz.getMethod("pirnt" ,String.class,String.class); m2.invoke(printUtil,"hello" ,"world" ); Method m3=clazz.getMethod("print" ); m3.invode(printUtil); }; catch (NoSuckMethodException e){ e.printStackTrace(); }; return ; }; }; class PrintUtil { public void print (int a,int b) { System.out.println(a+b); return ; }; public void print (String a,String b) { System.out.println(a.toUpperCase()+b.toUpperCase()); return ; }; public void print () { System.out.println("Hello world!" ); return ; }; };
注解 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 import java.lang.annotation.ElementType;@Target import java.lang.annotation.RetentionPolicy;@Retention @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface Test{ ... }; @Inherited 被自动继承@Documented 被javadoc文档化@Override 重写方法@Deprecated 已过时@SuppressWarnings("...") @SuppressWarnings({"...","..."}) @Target(...) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface CustomAnnotation{ int num () default 10 ; String name () default "a" ; String desc () default "b" ; }; public class AnnotationTest { @CustomAnnotation(name="c",desc="d") public void test1 () { ... }; @CustomAnnotation public void test2 () { ... }; }; public class MyAnnotationProcessor { public static void main (String[]args) { try { Class clazz MyAnnotationProcessor.class.getClassLoader().loadClass("com.demo.AnnotationTest" ); Field[]fields=clazz.getDeclaredFields(); for (Field field:fields){ CustomAnnotation myAnnotation=field.getAnnotation(CustomAnnotation.class); System.out.println("" +myAnnotation.name()+myAnnotation.num()+myAnnotation.desc()); }; Method[]methods=clazz.getMethods(); for (Method method:methods){ if (method.isAnnotationPresent(CustomAnnotation.class)){ CustomAnnotation myAnnotation=method.getAnnotation(CustomAnnotation.class); System.out.println("" +myAnnotation.name()+myAnnotation.num()+myAnnotation.desc()); }; }; }; catch (ClassNotFoundException e){ e.printStackTrce(); }; return ; }; };
Date类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 import java.util.Date;Date date=new Date (无或System.currentTimeMillis()); System.out.println(date.toString()); System.out.println(date.getTime()); Date date2=new Date (date.getTime()-1000 ); System.out.println(date.before(date2));
Calendar类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import java.util.Calendar;Calendar cal=Calendar.getInstance(); System.out.println(cal.getTime()); cal.set(年,月-1 ,日); System.out.println(cal.get(Calendar.YEAR));
1 2 3 4 5 6 7 8 9 10 11 12 import java.text.DateFormat;Date now=new Date (); DateFormat dateFormat=DateFormat.getDateInstance(DateFormat.MEDIUM); System.out.println(dateFormat.format(now)); now=dateFormat.parse("2018-07-25" ); System.out.println(now.toString());
1 2 3 4 5 import java.text.SimpleDateFormat;SimpleDateFormat simpleDateFormat=new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss:SSS" ); System.out.println(simpleDateFormat.format(new Date ())); long time=simpleDateFormat.parse(str).getTime();System.out.println(simpleDateFormat.format(time));
1 2 3 4 5 import java.time.format.DateTimeFormatter;import java.time.LocalDateTime;DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss" ); LocalDateTime time=LocalDateTime.parse("2018-07-25 10:00:00" ,formatter); System.out.println(formatter.format(time));
Unix时间戳 1 System.currentTimeMillis()/1000 ;
1 2 3 4 5 6 7 8 9 10 11 12 13 import java.io.FileInputStream;import java.io.InputStream;InputStream inputstream=new FileInputStream ("..." 或new File ("..." )); System.out.println(inputStream.read()); inputStream.close();
Reader类 1 2 3 4 5 6 7 8 9 10 11 12 13 import java.io.FileReader;import java.io.Reader;Reader reader=new FileReader ("..." ); System.out.println(reader.read());
OutputStream类 1 2 3 4 5 6 7 8 9 import java.io.*;File outputFile=new File ("..." ); OutputStream outputStream=new FileOutputStream (outputFile); outputStream.write(...); outputStream.close();
Writer类 1 2 3 4 5 6 7 8 9 import java.io.*;Writer writer=new FileWriter ("..." ); writer.write(...); writer.close();
系统预定义流 1 2 3 import java.io.*;BufferedReader reader=new BufferedReader (new InputStreamReader (System.in)); System.out.println(reader.readLine());
File类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import java.io.*;File file=new File ("..." ); boolean file.createNewFile() boolean file.isAbsolute() boolean file.canRead() boolean file.renameTo(new File ("..." )) boolean file.mkdirs() boolean file.isDirectory() String s[]=file.list(); File[] files=file.listFiles(); String file.getName(); boolean file.delete()
1 2 3 4 5 6 7 FileInputStream input=new FileInputStream ("..." 或new File ("..." )); FileOutputStream output=new FileOutputStream ("..." 或new File ("..." )); byte [] byteArray=new byte [input.available()];input.read(byteArray); output.write(byteArray); input.close(); output.close();
FileReader/Writer类 1 2 3 4 5 6 FileReader fileReader=new FileReader ("..." ); FileWriter fileWriter=new FileWriter ("..." ); char fileReader.read();fileWriter.write("..." ); fileReader.close(); fileWriter.close();
1 2 3 4 5 6 7 8 9 10 11 12 13 import java.io.*;FileInputStream input=new FileInputStream ("..." ,选填size); FileOutputStream output=new FileOutputStream ("..." ,选填size); BufferedInputStream bufferInput=new BufferedInputStream (input); BufferedOutputStream bufferOutput=new BufferedOutputStream (output); byte [] buffer=new byte [1024 ];int pufferInput.read(buffer);String content=null ; content+=new String (buffer,0 ,flag); bufferOutput.write(content.getBytes(),0 ,content.getBytes().length()); bufferOutput.flush(); bufferOutput.close(); bufferInput.close();
BufferedReader/Wirter类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 FileReader fileReader=new FileReader ("..." ); FileWriter fileWriter=new FileWriter ("..." ); BufferedReader reader=new BufferedReader (fileReader); BufferedWriter writer=new BufferedWriter (fileWriter); String reader.readLine(); reader.close(); writer.write("..." ); writer.newLine(); writer.flush(); writer.close();
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import java.io.*;File file=new File ("..." ); DataOutputStream out=new DataOutputStream (new FileOutputStream (file)); out.writeBoolean(...); out.writeByte(...); out.writeChar(...); out.writeShort(...); out.writeInt(...); out.writeLong(...); out.writeUTF("..." ); out.close(); DataInputStream in=new DataInputStream (new FileInputStream (file)); short in.readShort();int in.readInt();long in.readLong();boolean in.readBoolean();byte in.readByte();char in.readChar();in.close();
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import java.io.Serializable;public class Cat implements Serializable { public String name,desc; public Integer age; }; import java.io.*;Cat cat=new Cat (); FileOutputStream fileOut=new FileOutputStream ("*.ser" ); ObjectOutputStream out=new ObjectOutputStream (fileOut); out.writeObject(cat); out.close(); fileOut.close(); FileInputStream fileIn=new FileInputStream ("*.ser" ); ObjectInputStream in=new ObjectInputStream (fileIn); cat=(Cat)in.readObject; in.close(); filein.close();
xlsx 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import org.apache.poi.ss.usermodel.*;File file=new File ("*.xlsx" ); InputStream inputStream=new FileInputStream (file); Workbook workbook=WorkbookFactory.create(inputStream); inputStream.close(); Sheet sheet=workbook.getSheetAt(0 ); int rowLength=sheet.getLastRowNum()+1 ;Row row=sheet.getRow(int ); int colLength=row.getLastCellNum();Cell cell=row.getCell(int ); CellStyle cellStyle=cell.getCellStyle(); cell.setCellType(CellType.STRING); String cell.getStringCellValue(); cell.setCellValue("..." ); OutputStream out=new FileOutputStream (file); workbook.write(out);
zip 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import java.util.zip.*;public static String compress (String str) throws IOException{ if (str==null ||str.length()==0 ){ return str; }; ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream (); GZIPOutputStream gzipOutputStream=new GZIPOutputStream (byteArrayOutputStream); gzipOutputStream.write(str.getBytes()); gzipOutputStream.close(); return byteArrayOutputStream.toString("ISO-8859-1" ); }; public static String uncompress (String str) throws IOException{ if (str==null ||str.length()==0 ){ return str; }; ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream (); ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream (str.getBytes("ISO-8859-1" )); GZIPInputStream gzipInputStream=new GZIPInputStream (byteArrayInputStream); byte []buffer=new byte [256 ]; int n; while ((n=gzipInputStream.read(buffer))>=0 ){ byteArrayOutputStream.write(buffer,0 ,n); }; return byteArrayOutputStream.toString(); };
异常处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 throw new RuntimeException ("..." );public static void test () throws Exception{ ... }; try { throw ...; } catch (Exception e){ e.printStackTrace(); System.out.println(e.getClass().getName()); System.out.println(e.getMessage()) } catch (... e){ ... } finally { }; public class DefineException extends Exception { public DefineException (String ErrorMessage) { super (ErrorMessage); }; };
Thread 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 public class TreadDemo extends Thread { private Thread t; private String threadName; public ThreadDemo (String name) { threadName=name; }; public void run () { try { ... } catch (InterruptedException e){ ... }; return ; }; public void start () { if (t==null ){ t=new Thread (this ,threadName); t.start(); return ; }; this .start(); return ; }; }; public class Demo { public static void main (String[]args) { ThreadDemo thread=new ThreadDemo ("..." ); thread.start(); return ; }; };
Callable&Future接口 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 import java.util.concurrent.*;public class Demo implements Callable <Integer>{ public static void main (String[]args) { Demo demo=new Demo (); FutureTask<Integer>ft=new FutureTask <>(demo); System.out.println(Thread.currentThread().getName()); new Thread (ft,"..." ).start(); try { System.out.println("" +ft.get()); } catch (Exception e){ e.printStackTrace(); }; return ; }; @Override public Integer call () throws Exception{ ... return ...; }; };
生命周期 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 public class Demo implements Runnable { public synchronized void notifying () throws InterruptedException{ notify(); return ; }; public synchronized void waiting () throws InterruptedException{ wait(); return ; }; public void run () { try { Thread.sleep(100 ); waiting(); } catch (Exception e){ e.printStackTrace(); }; return ; }; public static void main (String[]args) throws InterruptedException{ Demo demo=new Demo (); Thread thread=new Thread (demo); System.out.println(thread.getState()); thread.start(); System.out.println(thread.getState()); Thread.sleep(50 ); System.out.println(thread.getState()); Thread.sleep(100 ); System.out.println(thread.getState()); demo.notifying(); System.out.println(thread.getState()); thread.join(); System.out.println(thread.getState()); } };