Java 常用工具方法

时间:2022-08-31 17:29:43

1.去除文件中的空行:

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();
}
}

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

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 + " ");
}
}
}