1.获取项目中resources目录下的文件流
//获取项目中resources目录下的文件流
InputStream inputStream = null;
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if(contextClassLoader != null){
inputStream = contextClassLoader.getResourceAsStream("fileName");
}else{
inputStream = ClassLoader.getSystemResourceAsStream("fileName");
}
2.java -jar 跑main方法
第一种指定main方法所在的类
java -cp jar包名称 main方法所在类
java -cp syy.jar com.syygl.Test
第二种在MANIFEST.MF中指定main方法,可以通过maven打包指定
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.3</version>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>main方法所在的类</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>assembly</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
3.遍历目录下的文件
static List<String> fileNameList = new ArrayList<String>();
public static List<String> getAllFileNames(String filePath){
File file = new File(filePath);
File[] files = file.listFiles();
for (File file1: files) {
if(file1.isDirectory()){
getAllFileNames(file1.getAbsolutePath());
}else{
fileNameList.add(file1.getAbsolutePath());
}
}
return fileNameList;
}
4.java如何读取处理大文件
5.java判断文件中是否包含某些关键字
6.Mysql索引失效
1、or左右只有一个有索引
2、like查询以%开头
3、对查询的列上有函数或运算
4、字符类型的索引列未加引号,导致运算
5、没有使用联合索引的第一个字段
6、在索引字段上使用not,<>,!=
type 字段比较重要, 它提供了判断查询是否高效的重要依据依据. 通过 type 字段, 我们判断此次查询是 全表扫描 还是 索引扫描 等.
ALL < index < range ~ index_merge < ref < eq_ref < const < system
7.回滚事务
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
8.定时任务
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
//某任务上次理论启动时间+间隔时间就是下次启动时间。
private void initScheduler() {
this.scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
initCacheData();
} catch (Throwable ignored) {
}
}
}, 20, 60, TimeUnit.SECONDS);
//某任务上次结束时间+间隔时间就是下次启动时间。
this.scheduler.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
initCacheData();
} catch (Throwable ignored) {
}
}
}, 20, 60, TimeUnit.SECONDS);
//抛异常后定时任务会全部结束,所以要cache住异常
}
9.Excel读写
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.springframework.util.StringUtils;
import java.io.*;
/*
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
*/
public class ExcelDemo {
public static void main(String[] args) {
analysisExcel();
}
public static void analysisExcel() {
Workbook workbook = null;
//创建File 读取文件
File Inputfile = new File("C:\\Users\\user\\Desktop\\123.xls");
File outputfile =new File("C:\\Users\\user\\Desktop\\任务重推-处理到59行.sql");
try {
//使用字符流接File的数据
FileInputStream fileInputStream = new FileInputStream(Inputfile);
//workbook去接fileInputStream,读取到excel文件
workbook = Workbook.getWorkbook(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream(outputfile);
BufferedOutputStream bw = new BufferedOutputStream(fileOutputStream); //输出语句
//判断是哪一个工作簿,用Sheet类
Sheet readfirst = workbook.getSheet(0);
//获取有效行数
int rows = readfirst.getRows();
//获取有效列数
int clomns = readfirst.getColumns();
System.out.println("row:" + rows);
System.out.println("clomns:" + clomns);
for(int i =1;i<rows;i++) {
//循环得到每一行的单元格对象
Cell[] cells = readfirst.getRow(i);
//根据每一个单元格对象获取里面的值
String r= cells[0].getContents();
String c = cells[1].getContents();
String p =cells[2].getContents();
if(!StringUtils.isEmpty(r) && !StringUtils.isEmpty(c) && !StringUtils.isEmpty(p)){
String str = "'"+r+"', '"+c+"', '"+p+"', '"+c+"'\n";
System.out.println(str);
byte[] outputbyte = str.getBytes();
bw.write(outputbyte);
bw.flush();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
}
}
10.对象转换工具
public class BeanConvertUtils extends BeanUtils {
/**
* 转换对象
*
* @param source 源对象
* @param targetSupplier 目标对象供应方
* @param <S> 源对象类型
* @param <T> 目标对象类型
* @return 目标对象
*/
public static <S, T> T convertTo(S source, Supplier<T> targetSupplier) {
if (null == source || null == targetSupplier) {
return null;
}
T target = targetSupplier.get();
copyProperties(source, target);
return target;
}
/**
* 转换对象
*
* @param sources 源对象list
* @param targetSupplier 目标对象供应方
* @param <S> 源对象类型
* @param <T> 目标对象类型
* @return 目标对象list
*/
public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier) {
if (null == sources || null == targetSupplier) {
return null;
}
List<T> list = new ArrayList<>(sources.size());
for (S source : sources) {
T target = targetSupplier.get();
copyProperties(source, target);
list.add(target);
}
return list;
}
}
11将内容输出到文件
public class WriteToFileUtlis {
BufferedOutputStream bw = null;
public void writeToFile(String str) {
try {
if (bw == null) {
File outputfile = new File("C:\\Users\\user\\Desktop\\test.txt");
if (!outputfile.exists()) {
outputfile.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(outputfile);
bw = new BufferedOutputStream(fileOutputStream); //输出语句
}
bw.write((str + "\n").getBytes(StandardCharsets.UTF_8));
bw.flush();
}catch (Exception e){
}
}
}
12 运行注释掉的代码
public static void main(String[] args) {
// \u000d System.out.println("syytest");
}
13 @MapperScan的另一种加载方式
使用spring.factories文件加载,工具包中使用,依赖的项目就可以不用再手动添加
14 springBoot获取注解的全部类
public final class DoClassManageUtils {
private static Map<String, Class> handlerMap = new HashMap<String, Class>();
private static void initDoClass() {
//spring工具类,可以获取指定路径下的全部类
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
try {
String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath("com.xx.xx") + "/**/*DO.class";
Resource[] resources = resourcePatternResolver.getResources(pattern);
//MetadataReader 的工厂类
MetadataReaderFactory readerfactory = new CachingMetadataReaderFactory(resourcePatternResolver);
for (Resource resource : resources) {
//用于读取类信息
MetadataReader reader = readerfactory.getMetadataReader(resource);
//扫描到的class
String classname = reader.getClassMetadata().getClassName();
Class<?> clazz = Class.forName(classname);
//判断是否有指定主解
TableName anno = clazz.getAnnotation(TableName.class);
if (anno != null) {
//将注解中的类型值作为key,对应的类作为 value
handlerMap.put(anno.value(), clazz);
}
}
} catch (Exception e) {
}
}
public static Class getDoClass(String tableName) {
Class aClass = handlerMap.get(tableName);
if (null == aClass) {
try {
initDoClass();
} catch (Throwable t) {
}
}
return handlerMap.get(tableName);
}
}
15 反射获取值和设置值
public static String getFieldValueByFieldName(String fieldName, Object object) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
//对private的属性的访问
field.setAccessible(true);
return (String) field.get(object);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void setFieldValueByFieldName(String fieldName, Object object, String value) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
//对private的属性的访问
field.setAccessible(true);
field.set(object, value);
} catch (Exception e) {
e.printStackTrace();
}
}
16 springBoot加载自定义配置文件
通过spring.factories加载MyEnvironmentPostProcessor
org.springframework.boot.env.EnvironmentPostProcessor=\
xx.xx.MyEnvironmentPostProcessor
/**
自定义环境处理,在运行SpringApplication之前加载任意配置文件到Environment环境中
*/
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
//Properties对象
private final Properties properties = new Properties();
private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
//自定义配置文件
String[] profiles = {
"config/application-com.yml",
};
//循环添加
for (String profile : profiles) {
//从classpath路径下面查找文件
Resource resource = new ClassPathResource(profile);
//加载成PropertySource对象,并添加到Environment环境中
environment.getPropertySources().addLast(loadProfiles(resource));
}
}
//加载单个配置文件
private PropertySource<?> loadProfiles(Resource resource) {
if (!resource.exists()) {
throw new IllegalArgumentException("资源" + resource + "不存在");
}
try {
//从输入流中加载一个Properties对象
return this.loader.load("application-com", resource).get(0);
}catch (IOException ex) {
throw new IllegalStateException("加载配置文件失败" + resource, ex);
}
}
}
17 java 枚举的一个用法
public enum ConfigStatusEnum {
//配置状态0-未配置 1-已配置 2已配置有变更
STATUS_0("0", "未配置"),
STATUS_1("1", "已配置"),
STATUS_2("2", "有变更");
String status;
String message;
ConfigStatusEnum(String status, String message) {
this.status = status;
this.message = message;
}
public String getStatus() {
return status;
}
public String getMessage() {
return message;
}
public static String getMessage(String status) {
for (ConfigStatusEnum t : ConfigStatusEnum.values()) {
if (t.getStatus().equals(status)) {
return t.message;
}
}
return null;
}
}