1.文件管理

(1)获取不带扩展名的文件名

1
2
3
4
5
public static String getFileNameWithoutExtension(File file) {
String name = file.getName();
int lastIndexOf = name.lastIndexOf('.');
return lastIndexOf == -1 ? name : name.substring(0, lastIndexOf);
}

(2)删除目录及目录下的所有文件

1
2
3
4
5
6
7
8
  // Path directory = new File("c:\\a").toPath();
public void delDir(Path directory) {
try {
Files.walk(directory).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
} catch (Exception e) {
e.printStackTrace();
}
}

(3)解压缩文件

将sourceZipFilePath.zip文件解压缩到targetDir目里。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/** 
* sourceZipFilePath 压缩后的文件路径。 c:\a.zip
* targetDirPath 需要压缩的目录。不以"\"结尾。
* **/
public void unZipFile(String sourceZipFilePath, String targetDirPath) {
//如果父级目录不存在则创建;mkdir()则不会创建父级目录,直接停止。
new File(targetDirPath).mkdirs();
// 支持中文文件名和目录,压缩时也需设置GBK,才能解压缩成功。
try (ZipFile zip = new ZipFile(sourceZipFilePath,Charset.forName("GBK"))) {
Enumeration enums = zip.entries();
while (enums.hasMoreElements()) {
ZipEntry entry = (ZipEntry) enums.nextElement();
try(
BufferedInputStream bufferis = new BufferedInputStream(zip.getInputStream(entry));
BufferedOutputStream bufferos = new BufferedOutputStream(
new FileOutputStream(sourceDir + "\\" + entry.getName()));
){
byte[] b = new byte[1024];
int len = 0;
while ((len = bufferis.read(b)) != -1) {
bufferos.write(b, 0, len);
}
}
}
} catch (IOException e) {
LOGGER.log(Level.ERROR, "文件解压失败。");
e.printStackTrace();
}
}

(4)压缩文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void zipFile(List<String> sourceFile, String targetFile) {
// 支持中文文件名和目录,需设置GBK,解压缩时同样设置GBK,才能成功。(默认是UTF-8)
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(targetFile), Charset.forName("GBK"))) {
for (String f1 : sourceFile) {
if (new File(f1).exists()) {
try (FileInputStream f = new FileInputStream(f1)) {
ZipEntry zipEntry = new ZipEntry(new File(f1).getName());
zos.putNextEntry(zipEntry);
// 写入数据
byte[] buffer = new byte[1024];
int len;
while ((len = f.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}
}
}
} catch (Exception e) {
LOGGER.log(Level.ERROR, targetFile + "文件压缩失败。");
e.printStackTrace();
}
LOGGER.log(Level.INFO, targetFile + "文件压缩完成。");
}

2.日期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 1.Date类 当前时间: Wed Apr 09 14:16:36 CST 2025
Date now = new Date(); // 获取当前时间
System.out.println("当前时间: " + now);

// 2.Calendar类 当前时间: Wed Apr 09 14:16:36 CST 2025
Calendar calendar = Calendar.getInstance(); // 获取当前时间
System.out.println("当前时间: " + calendar.getTime());

// 2.1假设我们有一个Date对象,可以是任意的Date对象
Date date = new Date();
// 使用Calendar类来设置时间为6天前
// Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, -6);
// 获取6天前的Date对象
Date sixDaysAgo = calendar.getTime();
// 输出结果: 六天前的日期是: Fri Oct 04 07:23:35 CST 2024
System.out.println("六天前的日期是: " + sixDaysAgo);

// 3.LocalDateTime类(推荐) 当前时间: 2025-04-09T14:16:36.725400400
LocalDateTime now1 = LocalDateTime.now(); // 获取当前日期时间
System.out.println("当前时间: " + now1);
//3.1 当前时间增加1 当前时间增加1分钟: 2025-04-20T09:23:38.834047400
System.out.println("当前时间增加1分钟: " + now1.plusMinutes(1));
//3.2 时间比较 当前时间比较: 1
System.out.println("当前时间比较: " + ChronoUnit.MILLIS.between(now1,LocalDateTime.now()));;

// 4.Instant类 当前时间: 2025-04-09T06:18:45.938171700Z
Instant now2 = Instant.now(); // 获取当前时间戳(UTC)
System.out.println("当前时间now2: " + now2);
//当前时间(系统时区): 2025-04-09T14:18:45.938171700+08:00[Asia/Shanghai]
ZonedDateTime zonedNow = now2.atZone(ZoneId.systemDefault()); // 转换为系统默认时区的时间
System.out.println("当前时间(系统时区)now2: " + zonedNow);

3.XML文件读写

(1)读取带有命名空间的XML文件,并输出字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void exportXmlContent(String id,String uml) {
InputSource inputSource = new InputSource(uml);// uml="C:\\1125.uml";
try {
// 1.注册命名空间,定义xmi:id的命名空间前缀
String xmiNamespacePrefix = "xmi";
String xmiNamespaceUri = "http://www.omg.org/XMI";
xpath.setNamespaceContext(new NamespaceContextImpl(xmiNamespaceUri, xmiNamespacePrefix));
// 2.定义 Xpath 表达式,查询元素,读取xmi:id
XPath xpath = XPathFactory.newInstance().newXPath();
String xpathExpress = "//packagedElement[@xmi:id=\"" + id + "\"]";
Node node = (Node) xpath.evaluate(xpathExpress, inputSource, XPathConstants.NODE);
System.out.println(node.getNodeName() + "#"+node.getAttributes().getNamedItem("xmi:id") ;
// 3.导出元素内容
StringWriter sw = new StringWriter();
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
System.out.println(sw.toString());
} catch (Exception e) {
e.printStackTrace();
}
}

(2)Xml文件调用

Node 类型可以直接转换成Element类型,用于处理元素的属性设置。

1
2
3
4
5
6
7
8
9
10
11
XPathFactory xpathFactory = XPathFactory.newInstance();
xpath = xpathFactory.newXPath();
URL xmlpath = AXMLFactory.class.getClassLoader().getResource("Browser.xml");
inputSource = new InputSource(xmlpath.toString());
String xpathExpress ="//Elements/Element[@name='Package']";
NodeList nodeList = xpath.evaluate(xpathExpress, inputSource,XPathConstants.NODESET);
for(int i=0;i<nodeList.getLength();i++) {
Node node=nodeList.item(i);
Element el=(Element)node;
System.out.println(node.getNodeName()+";"+node.getNodeValue()+";"+el.getAttribute("name"));
}

4.stream

(1)filter 过滤(查找)元素

函数语法:
Stream<TreeElement> java.util.stream.Stream.filter(Predicate<? super TreeElement> predicate)
(a)filter(判断是否需要的元素).collect(保存为新的List输出).

1
2
3
4
5
6
7
8
9
10
// 过滤集合
List<TreeElement> tlist1=tlist.stream().filter(x->"name".equals(x.getName()))
.collect(Collectors.toList());
// users集合过滤出(输出元素集中任意)一个元素
User match = users.stream().filter((user) -> user.getId() == 1).findAny().get();
List<String> list = Arrays.asList("aa", "bb", "", "cc");
// 过滤为空的数据
List<String> filtered = list.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
// List 转字符串
String str = filtered.stream().collect(Collectors.joining(",")); // "aa,bb,cc"

(b)字符串数组(fileNames)中获取指定的元素(.msnotation)。如果为null,返回空字符串;不为null,返回指定字符。

1
2
String[] fileNames=new File(targetDir).list();
String ret=Stream.of(fileNames).filter(x->x.contains(".msnotation")).findFirst().orElseGet(()->"");

(2)map 遍历元素转换成新元素

map()方法是流(Stream)类中的一个中间操作方法,它接受一个函数作为参数,并将该函数应用于流中的每个元素,然后返回一个新的流,其中包含由该函数的结果组成的元素。

1
2
3
List<Integer> list = Arrays.asList(1, 3, 4, 99, 20);
// 获取对应的平方数
List<Integer> squaresList = list .stream().map( i -> i*i).distinct().collect(Collectors.toList());

(3)collect 保存数据集

(一般与map、filter联用,放在最后作为新数据保存。)
函数语法:
List<TreeElement> java.util.stream.Stream.collect(Collector<? super TreeElement, Object, List<TreeElement>> collector)
把数据流保存到新的数组或集合中。

1
2
3
4
5
6
7
Map<String, Stream> map = new HashMap<String, Stream>();
map.put("001", new Stream("张三","西安"));
map.put("002", new Stream("李四","铜川"));
List<Map<String, Stream>> list = new ArrayList()
list.add(map);
List<Stream> streams = list.stream().map(item -> item.get("001")).collect(Collectors.toList());
Map<String, Stream> aqglEmpVoMap = streams .stream().collect(Collectors.toMap(Stream::getEmpId, Stream-> Stream));

(4)summaryStatistics 输出最大、最小、平均值

1
2
3
List<Integer> list = Arrays.asList(1, 3, 4, 99, 20);
IntSummaryStatistics statistics = list.stream().mapToInt(x -> x).summaryStatistics();
// "最大值:" + statistics.getMax()+"最小值:" + statistics.getMin()+"平均数:" +statistics.getAverage());

(5)集合中交集、差集、并集

1
2
3
4
5
6
7
8
9
10
11
12
13
// 两个集合求交集
List<String> list1 = Arrays.asList("阿卫", "阿辉", "阿杰", "阿成");
List<String> list2 = Arrays.asList("阿悦", "阿楠", "阿洁", "阿锋");
List<String> collect = list1.stream().filter(list2::contains).collect(Collectors.toList());
// 集合差集
List<String> list3 = list1.stream().filter(item -> !list2.contains(item)).collect(toList()); //(list1 - list2)
list3 = list2.stream().filter(item -> !list1.contains(item)).collect(toList());//(list2 - list1)
// 并集
List<String> listAll = list1.parallelStream().collect(Collectors.toList());
List<String> listAll2 = list2.parallelStream().collect(Collectors.toList());
listAll.addAll(listAll2);
// 去重并集( distinct() )
List<String> listAllDistinct = listAll.stream().distinct().collect(Collectors.toList());

(6)Map转List

1
2
3
4
5
6
7
8
9
10
Map<String,String> map = new HashMap<>(3);
map.put("600519","贵州茅台");
map.put("601398","工商银行");
map.put("300750","宁德时代");
List<Object> list1 = map.entrySet().stream().map(ent ->ent.getKey()+":"+ent.getValue()).collect(Collectors.toList());
List<Object> list2 = map.entrySet().stream().map(ent -> ent.getKey()).collect(Collectors.toList());
List<Object> list3 = map.entrySet().stream().map(ent -> ent.getValue()).collect(Collectors.toList());
list1.forEach(listFor -> System.out.println(listFor));
System.out.println("map数据格式:" + map);
System.out.println("list数据格式:" + list1);

(7)List转Map

1
2
3
4
5
6
7
8
Stream streamTest = new Stream("张三","西安","13345");
List<Stream> list1 = new ArrayList<>();
list1.add(streamTest);
/*使用Collectors.toMap形式*/
Map result = list1.stream().collect(Collectors.toMap(p -> p.getIdcard(), p -> p.getName(), (k1, k2) -> k1));
//其中Collectors.toMap方法的第三个参数为键值重复处理策略,如果不传入第三个参数,当有相同的键时,会抛出一个IlleageStateException。
//或者
Map<String, String> result1 = list1.stream().collect(Collectors.toMap(Stream::getIdcard, Stream::getName));

5.反射调用

示例静态类

1
2
3
4
5
6
7
class MyClass {
public static String DATA="静态字段数据";

public static String myStaticMethod(int number, String text) {
return "Number: " + number + ", Text: " + text;
}
}

(1)调用带参数有返回值的静态方法

转换对象类型(用instanceof判断):MyClass mc=MyClass.cast(Class对象);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) {
try {
// 获取Class对象
Class<?> clazz = Class.forName("com.example.MyClass");
// 转换对象类型(instanceof用于判断):MyClass mc=MyClass.cast(Class对象);
// 获取指定的静态方法(类型自动转换到方法参数)。(方法名,参数类型1...N)
Method method = clazz.getMethod("myStaticMethod", int.class, String.class);
// 调用静态方法。(静态方法,第一参数设置为null,不是静态方法则设置为对象;第二个参数开始对应形参类型,没有形参则只需第一个参数)
Object result = method.invoke(null, 42, "Hello");
// 输出结果:Number: 42, Text: Hello
System.out.println("Return value: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}

(2)静态字段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Field field = clazz.getDeclaredField("LOADED_RESOURCESET");
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) {
try {
// 获取Class对象
Class<?> clazz = Class.forName("com.example.MyClass");
Field field = clazz.getDeclaredField("DATA");
// 静态字段,传递null作为参数
String str=(String)field.get(null);
// 输出结果:静态字段数据
System.out.println("Return value: " + str);
} catch (Exception e) {
e.printStackTrace();
}
}
}

6.Comparator排序

(1)先按sort字段排序,再中文名称排序。

1
2
3
4
5
// 定义中文排序规则(拼音)
Collator collator = Collator.getInstance(java.util.Locale.CHINA);
// 先按sort字段排序,再中文名称排序。
teList.sort(Comparator.<TreeElement>comparingDouble((obj -> Double.parseDouble(obj.getSort()))).
thenComparing((a,b)->collator.compare(a.getName(), b.getName())));

(2)先分组排序,再每个组内按中文排序

1
2
3
4
5
6
7
8
9
// 定义中文排序规则(拼音)
Collator collator = Collator.getInstance(java.util.Locale.CHINA);
// 1.按类别分组
Map<String, List<TreeElement>> map = treeList.stream() // 根据类别排序
.collect(Collectors.groupingBy(TreeElement::getModelTypeCnName));
// 2.每个分组内的元素按中文排序
map.forEach((key,value)->value.sort((a,b)->collator.compare(a.getName(), b.getName())));
// 3.对分组后的键按中文排序,并整理为有序Map
map=map.entrySet().stream().sorted(Map.Entry.comparingByKey(collator)).collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue, (oldVal, newVal) -> oldVal, LinkedHashMap::new));

7. java规范

1.包声明
2.导入声明
3.类或接口声明
4.常量声量
5.字段声明(按照普通字段、静态字段;再按照private、protected、public)
6.构造方法或初始块
7.方法声明(按照普通方法、静态方法)
8.内部类声明
示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.example.myapp;

import java.util.List;
import java.util.Map;
import java.io.IOException; // 根据需要添加其他导入语句

public class MyClass {
// 1.常量声明部分(如果有的话)
public static final int MAX_SIZE = 100; // 常量通常是大写字母命名。
// 2.字段声明部分(非静态字段)
private int id;
// 3.静态字段声明部分(如果有的话)例如:单例实例等。例如:instance等。
public static MyClass instance; // 静态字段通常排在非静态字段之后。例如:instance等。
// 构造方法或初始化块部分(如果有的话)例如:构造方法等。例如:构造方法等。
public MyClass() {

8.获取系统信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 1.当前java版本为:17.0.10
System.out.println("当前java版本为:" + System.getProperty("java.version"));
// 2.Java 运行时环境的安装目录:D:\eclipse\plugins\org.eclipse.justj.openjdk.hotspot.jre.full.win32.x86_64_17.0.10.v20240120-1143\jre
System.out.println("Java 运行时环境的安装目录:" + System.getProperty("java.home"));
// 3.当前操作系统为:Windows 10
System.out.println("当前操作系统为:" + System.getProperty("os.name"));
// 4.当前用户为:algz
System.out.println("当前用户为:" + System.getProperty("user.name"));
// 5.当前用户目录为:C:\Users\xxx
System.out.println("当前用户目录为:" + System.getProperty("user.home"));
// 6.当前工作目录为:D:\git\server-dev\modules\config
System.out.println("当前工作目录为:" + System.getProperty("user.dir"));
// 7.使用类加载器获取资源路径 Resource URL: file:/D:/git/modsim-glsp-server-dev/modules/config/target/classes/
URL resourceURL = CustomClass.class.getClassLoader().getResource("");
System.out.println("Resource URL: " + resourceURL);
// 8.读取`Manifest`文件获取JAR内资源路径(仅适用于JAR文件)Class Path from JAR:: file:/D:/git/modsim-glsp-server-dev/modules/config/target/classes/
String classpath = Input.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println("Class Path from JAR: " + classpath);
// 9.当前类路径的根目录: /D:/git/server-dev/modules/config/target/classes/
System.out.println("当前类路径的根目录:"+Input.class.getResource("/").getPath());
// 10.当前类路径:/D:/git/server-dev/modules/config/target/classes/com/xxx/server/config/kind/
System.out.println("当前类路径:"+Input.class.getResource("").getPath());

9.Map

(1)删除元素

1
2
3
4
// 删除value==null的元素,不改变map
map.keySet().removeIf(key -> map.get(key) == null);
// 删除value==null的元素,创建新的map
Map<String, String> filteredMap = map.entrySet().stream().filter(entry -> entry.getValue() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

10.Optional

1.ifPresent()

ifPresent 相当于判断 !=null , 不为空才执行里面的代码:

1
2
3
Student student1 = new Student("王五", 80);
Optional<Student> optional = Optional.ofNullable(student1);
optional.ifPresent(name -> System.out.println("student1不为空,姓名为:"+name.getName()));

2.ifPresentOrElse()

java 9里新增了 ifPresentOrElse(),当 Optional 里的值不为空则执行第一个参数里的代码,为空则执行第二个参数的代码,相当于 if-else :

1
2
3
Student student = new Student("王五", 80);
Optional<Student> optional = Optional.ofNullable(student);
optional.ifPresentOrElse( value -> System.out.println("student不为空,姓名:"+value.getName()), () -> System.out.println("student为空") );