JAVA学习札记

字符串操作:

字符串分割:String array[] = str.split("\t"); 

字符串截取:str.substring(0,2);

字符串比较:str1.equals(str2)

数组操作:

array定义:type[] 变量名 = new type[数组中元素的个数]; //eg: int[] a = new int[10];

                type变量名[] = new type[数组中元素的个数]; //eg: int a[] = new int[10];

                type[] 变量名 = new type[]{逗号分隔的初始化值}; //eg: int[] a = new int[]{1,2,3,4}; 或 int[] a = {1,2,3,4};

二维数组:  type[][] i = new type[2][3];(推荐)或:type i[][] = new type[2][3];

列表操作:

List定义:List<String> list=new ArrayList();

List赋值:list.add("apple");

List移除元素:list.remove("apple");

ArrayList初始化:ArrayList<String> list = new ArrayList(Arrays.asList("apple", "banana"));

判断是否包含某元素:list.contains("apple")

List长度:list.size();

List遍历:

方法(1):for(String str:list){System.out.println(str);}

方法(2):for (Iterator<String> s = list.iterator(); s.hasNext();) {String str=s.next(); 
            System.out.println(str);}

方法(3):for(int i=0;i<list.size();i++){System.out.println(list.get(i));}

hashmap操作:

HashMap定义:HashMap<String, Double> map = new HashMap<String, Double>(); 

HashMap赋值:map.put("key1", "value1");

判断是否包含key:map.containsKey("apple")

获取key-value:map.get("apple")

正则匹配:

Pattern pattern=Pattern.compile("[^a-zA-Z]");

Matcher matcher=pattern.matcher(str);

while(matcher.find()){System.out.println(matcher.group());}

JAVA读文件:

1.按行读取文件内容

package readFile;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
    public static void main(String[] args) throws FileNotFoundException,IOException{
        FileReader reader = new FileReader("resource/test.txt"); //input path
        BufferedReader br = new BufferedReader(reader);
        String str = null;
        while((str = br1.readLine()) != null) {
                System.Out.println(str);
        }
     br.close(); } }

JAVA 写文件

package writeFile;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException; 

public class Main {
    public static void main(String[] args) throws FileNotFoundException,IOException{
    BufferedWriter writer = new BufferedWriter(new FileWriter(new File("resource/wt.txt")));//write path
//FileWriter writer = new FileWriter("resource/wt.txt");//该方法也可以 writer.write(
"hello\tworld\r\n"); writer.close() } }

PS:若希望输入的新内容不覆盖文件已有的内容,则改为

BufferedWriter writer = new BufferedWriter(new FileWriter(new File("resource/wt.txt",true)));或
FileWriter writer = new FileWriter("resource/wt.txt",true);

 

posted @ 2014-12-01 17:45  小白菜的BLOG  阅读(219)  评论(0编辑  收藏  举报