
为方便处理数据:
高级语言-数据类型;
文件-文件类型(扩展名):文本文件;二进制文件
获取资源文件的两种方式
| 获取资源文件方式 | path写法 |
菜鸟雷区 |
|---|---|---|
Class.getResource(String path) |
path以/开头:则是从ClassPath根下获取 path不以/开头:默认是从此类所在的包下取资源 |
需要用类名获取,否则报空指针异常 |
ClassLoader.getResource(String path) |
ClassLoader.getResource的path中不能以/开头,path是默认是从根目录下进行读取的 |
Excel文件操作
Excel文件主要两种格式:.xls和.xlsx(Office2007以后的格式)
封装方法
引入依赖
<!--读取Excel(xlsx扩展名)格式文件--><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.2</version></dependency>
保存对象列表到.xlsx文件
//保存对象列表->.xlsx文件public static String writeExcel(List<CodeMap> list,String path) throws IOException {Workbook wb = new XSSFWorkbook();Sheet sheet = wb.createSheet();for (int i=0;i<list.size();i++){CodeMap codeMap = list.get(i);Row row = sheet.createRow(i);row.createCell(0).setCellValue(codeMap.getCityName());row.createCell(1).setCellValue(codeMap.getAdcode());row.createCell(2).setCellValue(codeMap.getCitycode());}FileOutputStream fos = new FileOutputStream(path);wb.write(fos);//关闭资源fos.close();wb.close();return "writeExcel success!!";}
读取Excel文件
//读取Excel文件->对象列表public static List<CodeMap> readExcel(String path) throws IOException, InvalidFormatException {//Workbook对应一个Excel文件对象//XSSFWorkbook对应 .xlsx格式Workbook wb = new XSSFWorkbook(new File(path));List<CodeMap> list = new ArrayList<>();//sheet表示一个工作表for (Sheet sheet : wb) {//Row表示一行for (Row row : sheet) {//Cell表示一个单元格String cityName = row.getCell(0).getStringCellValue();String adcode = row.getCell(1).getStringCellValue();//citycode有空指针异常String citycode = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue();list.add(new CodeMap(cityName, adcode, citycode));}}wb.close();return list;}
bug解决
bug:读取 空的单元格时 会报NullPointerException解决方法:Row.MissingCellPolicy.CREATE_NULL_AS_BLANK
参考
- 书籍:(Java编程的逻辑).文件
- Java中处理Excel文件及其他微软文档广泛使用POI类库
JSON文件操作
JSON文件就是存放JSONString封装方法
引入依赖
<!-- fastjson坐标,处理json --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.79</version></dependency>
写jsonString->json文件
//写入JSON文件public static String writeJson(String jsonString,String filePath){BufferedWriter br = null;try {br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath,false), StandardCharsets.UTF_8));br.write(jsonString);} catch (IOException e) {e.printStackTrace();} finally {if (br!=null){try {br.close();} catch (IOException e) {e.printStackTrace();}}}return "writeJson success!!";}
读json文件->String
读取json文件public static String readJson(String filePath){BufferedReader br = null;//StringBuilder用于拼接字符串StringBuilder jsonString = new StringBuilder();try {FileInputStream fis = new FileInputStream(filePath);br = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8));String temp ;while((temp = br.readLine())!=null){jsonString.append(temp);}} catch (IOException e) {e.printStackTrace();} finally {if (br!=null){try {br.close();} catch (IOException e) {e.printStackTrace();}}}return String.valueOf(jsonString);}
