java 代码碎片
2019-01-06 本文已影响0人
蓝天白云bubble
一、java 按行将一篇文本读入到 List 中(保留换行)
public static List<String> splitTextToLineList(String text) {
List<String> lines = new ArrayList<>();
String[] splits = text.split("\n");
for (int i = 0; i < splits.length; i++) {
if (i != splits.length - 1) {
lines.add(splits[i] + "\n");
} else if (i == splits.length - 1) {
if (text.endsWith("\n")) {
lines.add(splits[i] + "\n");
} else {
lines.add(splits[i]);
}
}
}
return lines;
}
二、以追加的方式写文件
public static void writeStrToFile(String fileName, String str) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
out.write(str);
out.close();
} catch (IOException e) {
System.out.println("exception occoured" + e);
}
}
三、反射的用法
package com.bluesky.bubble.paragraph.util;
public class ParagraphSpliterUtil {
private static boolean isFragmentaryOrdinalBlock(int begin, int end, String text) {
// TODO
return fragmentaryOrdinalBlock;
}
}
// ================================
@Test
public void testIsFragmentaryOrdinalBlock() throws Exception {
String text = "He is a good man, and he has a dog.";
Class<?> clazz = Class.forName("com.bluesky.bubble.paragraph.util.ParagraphSpliterUtil");
Constructor<ParagraphSpliterUtil> constructor = (Constructor<ParagraphSpliterUtil>) clazz.getConstructor();
ParagraphSpliterUtil spliterUtil = constructor.newInstance();
Method method = clazz.getDeclaredMethod("isFragmentaryOrdinalBlock", int.class, int.class, String.class);
method.setAccessible(true);
Boolean result = (Boolean) method.invoke(spliterUtil, 0, text.length(), text);
assertTrue(result);
}
四、对象实现 Comparable 接口
public class Span implements Comparable<Span>{
private int begin;
private int end;
public Span(int begin, int end) {
this.begin = begin;
this.end = end;
}
public int getBegin() {
return begin;
}
public void setBegin(int begin) {
this.begin = begin;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
@Override
public int compareTo(Span span) {
if (this.begin == span.getBegin()) {
return this.end - span.getEnd();
}
return this.begin - span.getBegin();
}
}
五、获取一个路径下的所有文件
public static List<File> getDataDirs(File topDir) {
List<File> annFiles = new ArrayList<>();
getAnnFilesRec(topDir, annFiles);
return annFiles;
}
private static void getAnnFilesRec(File topDir, List<File> annFiles) {
for (File file : topDir.listFiles()) {
if (file.isDirectory()) {
getAnnFilesRec(file, annFiles);
} else {
annFiles.add(file);
}
}
}
六、java 对象序列化与反序列化
// 序列化(非基础类型要实现Serializable接口,和序列号)
public static void main(String[] args) throws FileNotFoundException, IOException {
Map<String, Integer> map = new HashMap<>();
map.put("hi", 1);
map.put("good", 2);
ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(new File("./data/serialize-test")));
oo.writeObject(map);
oo.close();
}
// 反序列化
@SuppressWarnings({ "rawtypes", "unchecked", "resource" })
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("E:/Person.txt")));
Map<String, Integer> map = (Map) ois.readObject();
System.out.println(map.get("hi"));
}
七、java 中 OptionParser 的使用
import joptsimple.OptionParser;
import joptsimple.OptionSet;
public static void main(String[] args) {
OptionSet options = parseArgs(args);
String outputFile = (String) options.valueOf("output");
System.out.println("output: " + outputFile);
}
private static OptionSet parseArgs(String[] args) {
OptionParser parser = new OptionParser();
parser.accepts(OUTPUT_FILE).withOptionalArg().ofType(String.class).defaultsTo("output")
.describedAs("result output file");
OptionSet options = parser.parse(args);
return options;
}
八、base64对字符串进行编码和解码
// 编码
String asB64 = Base64.getEncoder().encodeToString("中华人民共和国".getBytes("utf-8"));
System.out.println(asB64); // 输出为: 5Lit5Y2O5Lq65rCR5YWx5ZKM5Zu9
// 解码
byte[] asBytes = Base64.getDecoder().decode("5Lit5Y2O5Lq65rCR5YWx5ZKM5Zu9");
System.out.println(new String(asBytes, "utf-8")); // 输出为: 中华人民共和国
九、通过某个字符串将一个字符串 list 拼接起来
import org.apache.commons.lang.StringUtils;
String result = StringUtils.join(list, "\n");
十、将一个字符串写入某个文件中
import org.apache.commons.io.FileUtils;
FileUtils.writeStringToFile(new File(outputPath), text);
十一、将一个文件中的内容读出
import java.nio.file.Files;
import java.nio.file.Paths;
byte[] encoded = Files.readAllBytes(Paths.get(filePath));
String text = new String(encoded, "UTF-8");