LoginSignup
18
22

More than 5 years have passed since last update.

Javaでよく使う関数まとめ

Last updated at Posted at 2016-01-24

よく使うけどよく忘れる関数のメモ。
今後もどんどん増やしていきたい。

文字列の検証用関数

先頭文字が大文字かどうか

    public boolean isFirstUpperCase(String str) {
        return Character.isUpperCase(str.charAt(0));
    }

全角文字を含むかどうか

    public boolean isContainEm(String str) {
        return str.length() < str.getBytes().length;
    }

文字が数字かどうか1

    public boolean isNumber(String str) {
        return str.matches("-?[0-9]*\\.?[0-9]+");
    }

文字が数字かどうか2

    public boolean isNumber2(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

文字がnullまたは空文字かどうか

    public boolean isNullString(String str) {
        return (str == null || str.length() == 0);
    }

文字列の部分一致

URLが存在するか

ファイル関係

ファイルの存在確認・書き込み可能確認

    /**
     * @param file:対象のファイル
     * @return:存在して書き込み可能ならtrue
     */
    public boolean isFile(File file) {
        return file != null && file.exists() 
                && file.isFile() && file.canWrite();
    }

ファイルの内容を文字列で取得

    /** 
     * @param fileName : 読み込むファイル名
     * @return ファイルの中身。読み込めなかったらnull
     * @throws IOException
     */
    public String file2String(String fileName) throws IOException {
        if(isNullString(fileName)) {
            return false;
        }
        File file = new File(fileName);
        if(isFile(file)) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                StringBuffer sb = new StringBuffer();
                int c;
                while ((c = br.read()) != -1) {
                    sb.append((char) c);
                }
                return sb.toString();
            } finally {
                br.close();
            }
        }
        return null;
    }

ファイルに追記or上書き

     /**
     * @param fileName  : 対象のファイル
     * @param text      : 追記する内容
     * @param isAdding  : trueなら追記,falseなら上書き
     * @return : 成功したらtrue
     */
    public boolean write2File(String fileName, String text, boolean isAdding) {
        if(isNullString(fileName)) {
            return false;
        }
        File file = new File(fileName);
        if(isFile(file)) {
            try {
                PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file, isAdding)));
                pw.write(text);
                pw.close();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

指定した文字を含む行をファイルから削除

    /**
     * @param fileName
     * @param deleteLetter
     * @throws IOException
     */
    public void deleteLine(String fileName, String deleteLetter) throws IOException {
        if(isNullString(fileName)) {
            return false;
        }
        File file = new File(fileName);
        if(isFile(file)) {
            BufferedReader br = null;
            StringBuffer sb = null;
            try {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    if(!isMatch(line, deleteLetter)) {
                        sb.append(line+"\n");
                    }
                }
                write2File(fileName, sb.toString(), false);
            } finally {
                br.close();
            }
        }
    }

ファイルの中身をソート

    /**
     * @param fileName
     */
    public void sortFileContents(String fileName) {
        String[] fileContents= null;
        try {
            fileContents  = file2String(fileName).split("\n");
            Arrays.sort(fileContents);
            String writeStr = "";

            for(int i=0; i<fileContents.length; i++) {
                writeStr += fileContents[i] + "\n";
            }
            write2File(fileName, writeStr, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

文字列変換系

Unicode文字列に変換する

    /**
     * @param original
     * @return
     */
    public String convert2Unicode(String original) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < original.length(); i++) {
            sb.append("\\" + String.format("\\u%04X", Character.codePointAt(original, i)));
        }
        return sb.toString();
    }

Unicode文字列から元の文字列に変換する

    /**
     * @param unicode
     * @return:unicodeじゃなければそのまま返す
     */
    public String convert2Oiginal(String unicode) {
        if(isMatch(unicode, "\\\\\\\\u")) {
            String[] codeStrs = unicode.split("\\\\\\\\u");
            int[] codePoints = new int[codeStrs.length - 1]; 
            for (int i = 0; i < codePoints.length; i++) {
                codePoints[i] = Integer.parseInt(codeStrs[i + 1], 16);
            }
            String encodedText = new String(codePoints, 0, codePoints.length);
            return encodedText;
        }
        return unicode;
    }

リストから配列へ

    public String[] list2Array(List<String> list) {
        return (String[])list.toArray(new String[list.size()]);
    }

配列からリストへ

    public List<String> array2List(String[] array) {
        return Arrays.asList(array);
    }
18
22
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
22