Java基本语法

字符串数组

String[] array=new String[]{"1","2","3"}   
for (Object x : array) {   
    System.out.println(x.toString()); //逐个输出数组元素的值   
}   
  
for(int i=0;i<array.length;i++){   
      array[i];   
}  

List遍历:

对于ArrayList来说速度比较快, 用for循环, 以size为条件遍历:

for(int i = 0 ; i < list.size() ; i++) {  
  system.out.println(list.get(i));  
} 

Map遍历:

比较高效:

for (Map.Entry<String, String> entry : map.entrySet()) {     
    System.out.println("key= " + entry.getKey() + " and value="+ entry.getValue());     
}     

Map排序:

List<Map.Entry<String, Integer>> infoIds =  
    new ArrayList<Map.Entry<String, Integer>>(map.entrySet());  
  
//排序  
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {     
    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {        
        //return (o2.getValue() - o1.getValue());   
        return (o1.getKey()).toString().compareTo(o2.getKey());  
    }  
});   

集合转换

数组转集合:

import org.apache.commons.collections.CollectionUtils;      
 
CollectionUtils.addAll(strList, strArray);  //添加  
List strList = Arrays.asList(strArray);     //返回新List对象  
 
CollectionUtils.addAll(strSet, strArray);     

集合转数组

直接使用Collection的toArray()方法  
Object[] o = strList.toArray()  
T[] toArray(T[] a);  

集合互转

Map到其他集合类:  
直接使用Map的values()方法  
List<String> ss = (ArrayList<String>) hm.values();  
Set<String> ss = (HashSet<String>) hm.values();  

List和Set的互转  
Set set = new HashSet(Arrays.asList(array)); //list-->set  
List list = new ArrayList(new Hashset());   //set-->list  

时间处理转换

字符串到Date

String string = “2016-10-24 21:59:06”;
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
Date date = sdf.parse(string);

Date到字符串

Date date = new Date();  
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
System.out.println(sdf.format(date));  
  
获取当前时间  
System.out.println(sdf.format(new Date()));// new Date()为获取当前系统时间  

写文件效率最高

FileReader fr = new FileReader("C:\\demo.txt");
BufferedReader bufr = new BufferedReader(fr);

FileWriter fw = new FileWriter("D:\\love.txt");
BufferedWriter bufw = new BufferedWriter(fw);

//写入特定编码:
File rst01 = new File("/home/abc.txt");
File rst02 = new File("/home/abc1.txt");

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(rst01), "UTF-8"));

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(rst02), "UTF-8"));
//一行一行的寫。  
String line = null;
try {
    while ((line = bufr.readLine()) != null) {
        bufw.write(line);
        bufw.newLine();
        bufw.flush();
    }  
    /*  一個字節一個字節的寫。 
     int ch = 0; 
     while((ch = bufr.read())!=-1){ 
         bufw.write(ch); 
     }*/
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        bufr.close();
        bufw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
        

正则

import java.util.regex.Matcher;    
import java.util.regex.Pattern;       
  
   Pattern pattern = Pattern.compile("W(or)(ld!)");    
   Matcher matcher = pattern.matcher(str);    
   while(matcher.find()){    
    System.out.println("Group 0:"+matcher.group(0));//得到第0组——整个匹配    
    System.out.println("Group 1:"+matcher.group(1));//得到第一组匹配——与(or)匹配的    
    System.out.println("Group 2:"+matcher.group(2));//得到第二组匹配——与(ld!)匹配的,组也就是子表达式    
    System.out.println("Start 0:"+matcher.start(0)+" End 0:"+matcher.end(0));//总匹配的索引    
    System.out.println("Start 1:"+matcher.start(1)+" End 1:"+matcher.end(1));//第一组匹配的索引
}

线程池的使用

首先创建一个线程类

public class FileVersionThreadTask implements Runnable {
    ArrayList<String> fileFullPathAndVesionList;
    String fileFullPathStr;
    CountDownLatch countDownLatch;

    public FileVersionThreadTask(ArrayList<String> fileFullPathAndVesionList, String fileFullPathStr, CountDownLatch countDownLatch) {
        this.fileFullPathAndVesionList = fileFullPathAndVesionList;
        this.fileFullPathStr = fileFullPathStr;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        String diskFileVersion = "";
        File fileFullPath = new File(fileFullPathStr);
        if (StringUtils.isNotBlank(fileFullPathStr) && fileFullPath.exists()) {
//            long start = System.currentTimeMillis();
            diskFileVersion = FileVersionUtil.getFileVersion(fileFullPath);
//            long end = System.currentTimeMillis();
        }
        //共享变量加锁访问
        synchronized (fileFullPathAndVesionList) {
            fileFullPathAndVesionList.add(fileFullPathStr + ":" + diskFileVersion);
        }
        //标志当前任务已完成,计数递减
        countDownLatch.countDown();
    }
}

新建线程池,并向其中添加线程,到队列(本例使用无界队列)

int threadCount = 20;
//创建核心线程与最大县城相同的线程池,其实相当于newFixedThreadPool。 
// keepAliveTime=0,如线程数超过核心线程数时,多余的线程等待新的Task的时间,本利犹豫最大和核心相同,此值无意义
//LinkedBlockQueue队列,代表无界队列,受限于内存大小
ExecutorService executorService = new ThreadPoolExecutor(threadCount, threadCount,
        0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>());
//countDownLatch记录多少任务处理完成的计数器,每个Task执行完会减一,知道为0时,await()才从阻塞状态返回,返回后,shutdown线程池
CountDownLatch countDownLatch = new CountDownLatch(fileFullPathList.size());
for (String fullPath : fileFullPathList) {
    executorService.execute(new FileVersionThreadTask(fileFullVesionRst, fullPath, countDownLatch));
}
try {
    System.out.println("waiting for get all file version");
    countDownLatch.await();
//            System.out.println("max:" + maxTimeFile.get("max") + ", file:" + maxTimeFile.get("name"));
    System.out.println("get all file version done, totally " + fileFullPathList.size());
} catch (InterruptedException e) {
    e.printStackTrace();
}
executorService.shutdown();

打jar包的pom配置, mvn package

    <build>
        <finalName>scylla-${scylla.version}</finalName>
        <sourceDirectory>src/main/java</sourceDirectory>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>apps/*</include>
                    <include>config/*</include>
                    <include>*.properties</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!--			<plugin>-->
            <!--				<groupId>org.apache.maven.plugins</groupId>-->
            <!--				<artifactId>maven-jar-plugin</artifactId>-->
            <!--				<configuration>-->

            <!--					<archive>-->
            <!--						<manifest>-->
            <!--							<mainClass>com.alibaba.solar.scylla.bootstrap.Starter</mainClass>-->
            <!--							<addClasspath>true</addClasspath>-->
            <!--							<classpathPrefix>lib/</classpathPrefix>-->
            <!--						</manifest>-->
            <!--						<manifestEntries>-->
            <!--							<Class-Path>config/</Class-Path>-->
            <!--						</manifestEntries>-->
            <!--					</archive>-->
            <!--					<classesDirectory>-->
            <!--					</classesDirectory>-->
            <!--				</configuration>-->
            <!--			</plugin>-->

            <!--<plugin>-->
            <!--<groupId>org.apache.maven.plugins</groupId>-->
            <!--<artifactId>maven-dependency-plugin</artifactId>-->
            <!--<executions>-->
            <!--<execution>-->
            <!--<id>copy</id>-->
            <!--<phase>package</phase>-->
            <!--<goals>-->
            <!--<goal>copy-dependencies</goal>-->
            <!--</goals>-->
            <!--<configuration>-->
            <!--<outputDirectory>-->
            <!--${project.build.directory}/lib-->
            <!--</outputDirectory>-->
            <!--</configuration>-->
            <!--</execution>-->
            <!--</executions>-->
            <!--</plugin>-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.2.1</version>
                <configuration>
                    <descriptors>
                        <!--<descriptor>src/main/assembly/assembly.xml</descriptor>-->
                        <!--<descriptor>src/main/assembly/assembly_acp.xml</descriptor>-->
                    </descriptors>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>com.alibaba.solar.scylla.bootstrap.Starter</mainClass>
                            <addClasspath>true</addClasspath>
                            <!--<mainClass>com.alibaba.solar.scyllaplugin.ProcessNode</mainClass>-->
                        </manifest>
                        <manifestEntries>
                            <Class-Path>./ config/</Class-Path>
                            <!--<Class-Path>config/</Class-Path>-->
                        </manifestEntries>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

java DEBUG:

jdb方式debug java程序: http://blog.csdn.net/arkblue/article/details/39718947

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值