Java 常用工具方法

来源:互联网 发布:奇兔刷机软件 编辑:程序博客网 时间:2024/05/09 19:27

1.java获取到两个list中的不相同的项

public class Test {    public static void main(String args[]){        List<String> list1 = new ArrayList<>();        list1.add("a");        list1.add("b");        list1.add("c");        List<String> list2 = new ArrayList<>();        list2.add("b");        list2.add("c");        list2.add("d");        for(String s1 : list1){            if(!list2.contains(s1)){                System.out.println("list2不包括:" + s1);            }        }        for(String s2 : list2){            if(!list1.contains(s2)){                System.out.println("list1不包括:" + s2);            }        }    }}

输出:

list2不包括:a
list1不包括:d

2.去除文件中的空行:

public class QuKongHang {    public static void main(String[] args) throws Exception {        File f1 = new File("E:\\1.txt");// 打开文件        FileInputStream in = new FileInputStream(f1);        BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8"));        String line = "";        while ((line = read.readLine()) != null) {            if (!line.equals("")) {                System.out.println(line);            }        }        read.close();    }}

3.将整个文件中的某个字符替换成另一个:

public class 文件字符转换 {    public static void main(String[] args) {        try {            BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("E:\\1.txt"))));//数据流读取文件            StringBuffer strBuffer = new StringBuffer();            for (String temp = null; (temp = bufReader.readLine()) != null; temp = null) {                if ((temp.indexOf("for") == -1) && (temp.indexOf("if") == -1)) {                    if (temp.indexOf("《") != -1) { //判断当前行是否存在想要替换掉的字符 -1表示存在                        temp = temp.replace("《", "<");                    }                    if (temp.indexOf("》") != -1) { //判断当前行是否存在想要替换掉的字符 -1表示存在                        temp = temp.replace("》", ">");                    }                }                strBuffer.append(temp);                strBuffer.append(System.getProperty("line.separator"));//行与行之间的分割            }            bufReader.close();            PrintWriter printWriter = new PrintWriter("E:\\1.txt");//替换后输出的文件位置            printWriter.write(strBuffer.toString().toCharArray());            printWriter.flush();            printWriter.close();        } catch (IOException e) {            e.printStackTrace();        }    }}

3.List去重

public class Test {    public static void main(String args[]) {        List<String> oldList = new ArrayList<>();        oldList.add("a");        oldList.add("b");        oldList.add("c");        oldList.add("b");        List<String> newList = new ArrayList<>();        for (String cd : oldList) {            System.out.print(cd + " ");            if (!newList.contains(cd)) {                newList.add(cd);            }        }        System.out.println();        for (String cd : newList){            System.out.print(cd + " ");        }    }}


原创粉丝点击