当前位置 : 主页 > 编程语言 > c++ >

json报文转Java源码(同名类情况用下划线连接)

来源:互联网 收集:自由互联 发布时间:2021-06-30
生成文件位置和读取文件位置在代码里自定义即可(菜鸟编写请多指教) 两个.java文件源码已经已上传 FileUtils.java import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import ja
生成文件位置和读取文件位置在代码里自定义即可(菜鸟编写请多指教)
两个.java文件源码已经已上传
FileUtils.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FileUtils {

    public static void main(String[] args) {
        batchRename("E:\\work\\icons", "video_living_%s");
    }

    /**
     * 批量重命�?
     *
     * @param formatter
     *            重命名格式,xxx %s xxx,其�?%s为原有名�?
     */
    private static void batchRename(String dirPath, String formatter) {
        for (File file : getAllFiles(dirPath)) {
            File newFile = new File(file.getParentFile(), String.format(formatter, file.getName()));
            copyFileByChannel(file, newFile);
        }
    }

    /**
     * 递归获取的文件列表集�?
     */

    /**
     * 获取指定目录下全部文�?
     *
     * @param dir
     *            根目录路�?
     * @return 获取到的文件列表
     */
    public static List
 
   getAllFiles(String dir) {
        return getAllFiles(new File(dir));
    }

    /**
     * 获取指定目录下全部文�?
     *
     * @param rootFile
     *            根目录文�?
     * @return 获取到的文件列表
     */

    private static List
  
    getAllFiles(File file) { // TODO Auto-generated method stub return null; } /** * 递归dir下全部文件并保存至allFiles * * @param dir * 发起递归的根目录 */ public static void getFiles(File dir) throws Exception { File[] fs = dir.listFiles(); for (int i = 0; i < fs.length; i++) { File file = fs[i]; if (fs[i].isDirectory()) { try { getFiles(fs[i]); } catch (Exception e) { e.printStackTrace(); } } else { } } } /** * 使用文件通道的方式复制文�? * * @param srcFile * 源文�? * @param tarFile * 复制到的新文�? */ public static void copyFileByChannel(File srcFile, File tarFile) { FileInputStream fi = null; FileOutputStream fo = null; FileChannel in = null; FileChannel out = null; try { fi = new FileInputStream(srcFile); fo = new FileOutputStream(tarFile); in = fi.getChannel();// 得到对应的文件�?�道 out = fo.getChannel();// 得到对应的文件�?�道 // 连接两个通道,并且从in通道读取,然后写入out通道 in.transferTo(0, in.size(), out); } catch (IOException e) { e.printStackTrace(); } finally { try { fi.close(); in.close(); fo.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 替换指定目录下全部java文件内符合自定义条件的字符串 * * @param rootPath * 根目录的绝对路径 * @param replaceString * key-原文�? value-�?要替换的文字 */ public static void replaceStringOfJava(String rootPath, Map
   
     replaceString) { // 获取全部文件 List
    
      files = FileUtils.getAllFiles(rootPath); for (File file : files) { // 如果不是java后缀的文�?,则跳�? if (!file.getName().endsWith(".java")) { continue; } // 将文件读取为�?整个字符�? String fileContent = readToString(file); // 是否有替换操�? boolean hasReplace = false; // 遍历替换map,依次替换全部字符�? for (Map.Entry
     
       entry : replaceString.entrySet()) { if (fileContent.contains(entry.getKey())) { fileContent = fileContent.replace(entry.getKey(), entry.getValue()); hasReplace = true; } } // 如果有替换操�?,则将替换后的新文件内容字符串写入回文件中�? if (hasReplace) { writeString2File(fileContent, file); } } } /** * 替换指定目录下全部java文件内符合自定义条件的字符串,支持正则 * * @param rootPath * 根目录的绝对路径 * @param replaceString * key-原文�? value-�?要替换的文字 */ public static void replaceAllStringOfJava(String rootPath, Map
      
        replaceString, String charSet) { // 获取全部文件 List
       
         files = FileUtils.getAllFiles(rootPath); for (File file : files) { // 如果不是java后缀的文�?,则跳�? if (!file.getName().endsWith(".java")) { continue; } // 将文件读取为�?整个字符�? String fileContent = readToString(file, charSet); // 是否有替换操�? boolean hasReplace = false; // 遍历替换map,依次替换全部字符�? for (Map.Entry
        
          entry : replaceString.entrySet()) { if (fileContent.contains(entry.getKey())) { fileContent = fileContent.replaceAll(entry.getKey(), entry.getValue()); hasReplace = true; } } // 如果有替换操�?,则将替换后的新文件内容字符串写入回文件中�? if (hasReplace) { writeString2File(fileContent, file, charSet); } } } /** * 删除无用java文件 * * @param rootPath * 根目录的绝对路径 */ public static void delNoUseJavaFile(String rootPath) { List
         
           files = getAllFiles(rootPath); out: for (File file : files) { if (!file.getName().endsWith(".java")) { continue; } for (File compareFile : files) { // 如果包含文件�?,则视为有使用 String fileContent = readToString(compareFile); if (fileContent.contains(getName(file))) { continue out; } } String absname = file.getAbsoluteFile().getName(); boolean delete = file.delete(); System.out.println(absname + " ... delete=" + delete); } } /** * 获取代码行数详情,包括�?/空行/注释/有效代码各个行数 * * @param rootPath * 根目录的绝对路径 */ public static void getCodeLinesDetail(String rootPath) { // 全部文件中行�? int allLines = 0; // 全部文件中空行数 int allEmptyLines = 0; // 全部文件中代码行�? int allCodeLines = 0; // 全部文件中注释行�? int allAnnoLines = 0; List
          
            files = FileUtils.getAllFiles(rootPath); for (File file : files) { // TODO 只统计java和xml代码 if (file.getName().endsWith(".java") || file.getName().endsWith(".xml")) { FileReader fr; try { fr = new FileReader(file); BufferedReader bufferedreader = new BufferedReader(fr); String line; // 是否属于多行注释 boolean multiLineAnno = false; while ((line = bufferedreader.readLine()) != null) { allLines++; // 空行 if (line.trim().equals("")) { allEmptyLines++; continue; } // 单行注释 if (line.contains("//")) { allAnnoLines++; continue; } // 如果还是在多行注释中 if (multiLineAnno) { allAnnoLines++; // 如果本行包含多行注释结束�?,结束 if (line.contains("*/")) { multiLineAnno = false; } continue; } // 多行注释�?�?(包括/*�?/**) if (line.contains("/*")) { allAnnoLines++; multiLineAnno = true; continue; } // 有效代码 allCodeLines++; } fr.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("文件总行数为�?" + allLines); System.out.println("文件空行数为�?" + allEmptyLines); System.out.println("文件注释行数为:" + allAnnoLines); System.out.println("文件有效代码行数为:" + allCodeLines); System.out.println("--------------------"); // TODO 计算比例规则�? 注释行数/有效代码�? float percent = (float) allAnnoLines / allCodeLines * 100; // 格式化百分比,保留2位小�? %50.00 DecimalFormat df = new DecimalFormat("0.00"); System.out.println("注释比例(注释行数/有效代码�?): %" + df.format(percent)); } /** * 获取代码行数,只统计java/xml后缀的文�? * * @param rootPath * 根目录的绝对路径 */ public static void getCodeLines(String rootPath) { int allLines = 0; List
           
             files = getAllFiles(rootPath); for (File file : files) { if (file.getName().endsWith(".java") || file.getName().endsWith(".xml")) { int lines = getLines(file); allLines += lines; } } System.out.println(allLines); } /** * 获取文件内文本的行数 */ public static int getLines(File file) { int lines = 0; FileReader fr; try { fr = new FileReader(file); BufferedReader bufferedreader = new BufferedReader(fr); while ((bufferedreader.readLine()) != null) { lines++; } fr.close(); } catch (IOException e) { e.printStackTrace(); } return lines; } public static File getFileByName(String proPath, String filename) { File tarFile = null; List
            
              files = FileUtils.getAllFiles(proPath); for (File file : files) { String fileName = file.getName(); if (fileName.equals(filename)) { tarFile = file; break; } } return tarFile; } /** * 获取文件�?,去除后缀部分 */ public static String getName(File file) { String name = file.getName(); name = name.substring(0, name.lastIndexOf(".")); // 如果�?.9.png结尾�?,则在去除.png后缀之后还需要去�?.9的后�? if (file.getName().endsWith(".9.png")) { name = name.substring(0, name.lastIndexOf(".")); } return name; } /** * 获取文件�?,去除后缀部分 */ public static String getName(String fileAbsPath) { File file = new File(fileAbsPath); return getName(file); } /** * 文件名和后缀分开 */ public static String[] getNameMap(File file) { String[] nameMap = new String[2]; String name = file.getName(); name = name.substring(0, name.lastIndexOf(".")); // 如果�?.9.png结尾�?,则在去除.png后缀之后还需要去�?.9的后�? if (file.getName().endsWith(".9.png")) { name = name.substring(0, name.lastIndexOf(".")); } nameMap[0] = name; nameMap[1] = file.getName().replaceFirst(name, ""); return nameMap; } /** * 将文件读取为字符�? */ public static String readToString(File file) { Long filelength = file.length(); byte[] filecontent = new byte[filelength.intValue()]; try { FileInputStream in = new FileInputStream(file); in.read(filecontent); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { // 获取文件的编码格�?,再根据编码格式生成字符串 String charSet = getCharSet(file); return new String(filecontent, charSet); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } public static String parseCharset(String oldString, String oldCharset, String newCharset) { byte[] bytes; try { bytes = oldString.getBytes(oldCharset); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new RuntimeException("UnsupportedEncodingException - oldCharset is wrong"); } try { return new String(bytes, newCharset); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new RuntimeException("UnsupportedEncodingException - newCharset is wrong"); } } /** * 根据指定编码格式将文件读取为字符�? */ public static String readToString(File file, String charSet) { Long filelength = file.length(); byte[] filecontent = new byte[filelength.intValue()]; try { FileInputStream in = new FileInputStream(file); in.read(filecontent); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { return new String(filecontent, charSet); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } /** * 将文件内容以行为单位读取 */ public static ArrayList
             
               readToStringLines(File file) { ArrayList
              
                strs = new ArrayList
               
                (); FileReader fr = null; BufferedReader br = null; try { fr = new FileReader(file); br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { strs.add(line); } } catch (IOException e) { e.printStackTrace(); return null; } finally { if (br != null) { try { br.close(); } catch (IOException ignored) { } } if (fr != null) { try { fr.close(); } catch (IOException ignored) { } } } return strs; } /** * 搜索某目录下�?有文件的文本�?,是否包含某个字段,如果包含打印改文件路�? * * @param path * 搜索目录 * @param key * 包含字段 */ public static void searchFileContent(String path, String key) { List
                
                  allFiles = FileUtils.getAllFiles(path); for (File file : allFiles) { String string = FileUtils.readToString(file); if (string.contains(key)) { System.out.println(file.getAbsoluteFile()); } } } /** * 获取文件编码格式,暂只判断gbk/utf-8 */ public static String getCharSet(File file) { String chatSet = null; try { InputStream in = new java.io.FileInputStream(file); byte[] b = new byte[3]; in.read(b); in.close(); if (b[0] == -17 && b[1] == -69 && b[2] == -65) { chatSet = "UTF-8"; } else { chatSet = "GBK"; } } catch (IOException e) { e.printStackTrace(); } return chatSet; } /** * 将字符串写入文件 */ public static void writeString2File(String str, File file, String encoding) { BufferedWriter writer = null; try { if (!file.exists()) { file.createNewFile(); } writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding)); writer.write(str); } catch (IOException e) { e.printStackTrace(); } finally { try { writer.close(); } catch (IOException e) { writer = null; e.printStackTrace(); } } } public static void writeString2File(String str, File file) { writeString2File(str, file, getCharSet(file)); } /** * 将字节数组写入文件!!! 没用到!!!�? */ public static void writeBytes2File(byte[] bytes, File file) { FileOutputStream fos = null; try { if (!file.exists()) { file.createNewFile(); } fos = new FileOutputStream(file); fos.write(bytes); } catch (IOException e) { e.printStackTrace(); } finally { try { fos.close(); } catch (IOException e) { fos = null; e.printStackTrace(); } } } }
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
 
Json2JavaBean.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Stack;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

/**
 * @author chenShuangMing
 *
 *         2017年7月10日 下午3:20:39
 */
public class Json2JavaBean {
    public final static String FILE_PATH = "d:\\birth"; // 生成文件的位置
    public final static String CLASS_HEAD_NAME = "public class ";
    public final static String FUHAO_1 = " {";
    public final static String FUHAO_2 = " }";
    public final static String FUHAO_3 = "\r\n\r\n};";
    public final static String HUAN_HANG1 = "\r\n";
    public final static String HUAN_HANG2 = ";\r\n";
    private static String inputPath = "D:\\5.txt"; // 读取文件的位置
    public final static String ROOT = "ROOT";

    /**
     * end时处理同名curName的方法
     *
     * @param sameMap
     * @param nameList
     * @param curName
     * @return
     */
    public final static String newCurNameEnd(LinkedHashMap
 
  > sameMap, List
  
    nameList, String curName) { List
   
     samelistEnd = sameMap.get(curName); String nameEnd = curName; if (samelistEnd != null && !samelistEnd.isEmpty()) { curName = samelistEnd.get(samelistEnd.size() - 1);// 取出curName的值 samelistEnd.remove(samelistEnd.size() - 1); sameMap.put(nameEnd, samelistEnd); } nameList.remove(nameList.size() - 1); return curName; } /** * start时处理同名curName的 * * @param curName * @param nameStart * curName进来的初始值 * @param nameList * nameList装所有的进来的初始curName * @param sameMap * 装所有同名curName的map ,key是startName,value是装所有拼好的curName的集合 * @return */ public final static String newCurNameStart(String curName, List
    
      nameList, LinkedHashMap
     
      > sameMap) { String nameStart = curName; if (nameList.contains(curName)) {// 同名情况发生 String join = ""; for (String str : nameList) { join += str + "_"; } System.out.println("------------join:" + join); curName = join + curName; // 放在mapSame
      
       >中 List
       
         sameListStart = sameMap.get(nameStart);// 装拼好的,用于end对应start if (sameListStart == null) { sameListStart = new ArrayList
        
         (); } sameListStart.add(curName); sameMap.put(nameStart, sameListStart); } nameList.add(nameStart);// nameList装所有的进来的初始curName return curName; } public static void main(String[] args) { JsonFactory f = new JsonFactory(); ArrayList
         
           sbList = new ArrayList
          
           (); LinkedHashMap
           
            > mapCount = new LinkedHashMap
            
             >();// 计数的map LinkedHashMap
             
              > sameMap = new LinkedHashMap
              
               >(); List
               
                 nameList = new ArrayList
                
                 (); try { String content = FileUtils.readToString(new File(inputPath), "UTF-8");// 取到json字符串 JsonParser jp = f.createJsonParser(content); StringBuffer sbBuffer = null; Integer count = 0; Stack
                 
                   array_name = new Stack
                  
                   (); while (jp.nextToken() != null) { JsonToken token = jp.getCurrentToken(); String curName = jp.getCurrentName(); String tokenName = token.toString(); if (tokenName.equals("START_OBJECT")) { System.out.println("START_OBJECT处理之前: " + curName); // 返回curName的值的方法 if (curName == null) { curName = returnCurName(array_name, curName);// 要么是root,要么是array_name的尾元素名 ClsFile clsFile = createClsHead(sbList, curName); sbBuffer = clsFile.getContent(); } else { // 写同名处理的代码部分,因为下面要拼写完成的。 curName = newCurNameStart(curName, nameList, sameMap); creatFieldName(sbBuffer, curName, curName.toUpperCase()); ClsFile clsFile = createClsHead(sbList, curName.toUpperCase()); sbBuffer = clsFile.getContent(); } System.out.println("START_OBJECT处理之后: " + curName); List
                   
                     list = mapCount.get(curName); if (list == null) { list = new ArrayList
                    
                     (); } list.add(count); // 计数 count++; mapCount.put(curName, list); } else if (tokenName.equals("END_OBJECT")) { System.out.println("END_OBJECT处理之前: " + curName); // 当curName=null时返回curName的值 if (curName == null) { curName = returnCurName(array_name, curName);// 要么是root,要么是array_name的尾元素名 } else { // 写同名处理的代码部分,因为下面要拼写完成的 curName = newCurNameEnd(sameMap, nameList, curName); } System.out.println("END_OBJECT处理之后: " + curName); // 3.把类封底儿(+ }) addLast(sbList, curName); // 找到正确位置的方法 int backCount = findCount(curName, mapCount);// backCount是上一级在sbList中的位置 System.out.println("----------------------sbList是:" + sbList); System.out.println("--------------------sbList在backCount " + backCount + " 位置的类名是:" + sbList.get(backCount).getClassName()); sbBuffer = sbList.get(backCount).getContent(); if (ROOT.equals(curName)) { break; } } else { if (tokenName.equals("START_ARRAY")) { creatArrayFieldName(sbBuffer, curName.toUpperCase(), "List"); array_name.push(curName.toUpperCase()); } if (tokenName.equals("END_ARRAY")) { array_name.pop(); } if (!tokenName.equals("FIELD_NAME")) { if (tokenName.equals(JsonToken.VALUE_NUMBER_INT.toString())) { creatFieldName(sbBuffer, jp.getCurrentName(), "int"); } if (tokenName.equals(JsonToken.VALUE_STRING.toString())) { creatFieldName(sbBuffer, jp.getCurrentName(), "String"); } if (tokenName.equals(JsonToken.VALUE_TRUE.toString()) || tokenName.equals(JsonToken.VALUE_FALSE.toString())) { creatFieldName(sbBuffer, jp.getCurrentName(), "Boolean"); } } } } for (int j = 0; j < sbList.size(); j++) { System.out.println("元素中的位置:" + j + "-------------->" + "该位置的值是:" + sbList.get(j)); } // 去除sbList中同名的类和写入文件的操作 sbList = sameClassAndWriteFile(sbList); } catch (Exception e) { e.printStackTrace(); } } /** * 找出正确的位置 * * @param curName * @return */ public final static Integer findCount(String curName, LinkedHashMap
                     
                      > mapCount) { // 找到正确位置的方法 String beforeCurName = ""; List
                      
                        arr = new ArrayList<>(); arr.addAll(mapCount.keySet()); int index = arr.indexOf(curName); System.out.println("============arr:" + arr + " curName:" + curName + " index:" + index); if (index >= 1) { beforeCurName = arr.get(index - 1); } else { return 0; } List
                       
                         list = mapCount.get(beforeCurName); System.out.println("============beforeCurName的list是:" + list); Integer c = list.get(list.size() - 1); // 把key=curName的这个位置元素删掉 mapCount.remove(curName); return c; } /** * 当curName=null时返回curName的值得方法 */ public final static String returnCurName(Stack
                        
                          array_name, String curName) { curName = ""; if (array_name.size() > 0) { curName = array_name.get(array_name.size() - 1).toUpperCase(); } else { curName = ROOT; } return curName; } /** * 校验同名的问题(暂没用到) * * @param list * @param curName * @return true不重复,false重复 */ public final static boolean checkRepeat(List
                         
                           list, String curName) { if (!list.isEmpty()) { if (list.contains(curName)) { return false;// 重复的话返回false; } } return true; } /** * 在类的底部加上 } */ public final static void addLast(ArrayList
                          
                            sbList, String curName) { for (ClsFile cls : sbList) { if (curName.equalsIgnoreCase(cls.getClassName()) && cls.getContent().toString().indexOf(FUHAO_3) == -1) { // 只会有一个同名类文件 StringBuffer sb = cls.getContent(); sb.append(FUHAO_3); break; } } } /** * 除去sblist中同名的类 * * @param sbList * @return */ public final static ArrayList
                           
                             sameClassAndWriteFile(ArrayList
                            
                              sbList) { // 处理sbList中同名字的类,保证classname没有重复 for (int i = 0; i < sbList.size(); i++) { ClsFile cls = sbList.get(i); StringBuffer str = cls.getContent(); String className = cls.getClassName(); int num = 0; for (int n = 0; n < sbList.size(); n++) { if (className.equals(sbList.get(n).getClassName())) { num++; } } if (num >= 2) { sbList.remove(i); i--; } else { System.out.println("=========ClassName: " + className + "======================================" + i); System.out.println(str.toString()); writeClassFile(className, str.toString()); } } return sbList; } /** * 写入文件的方法 * * @param sbList */ public final static void writeFile(ArrayList
                             
                               sbList) { for (int i = 0; i < sbList.size(); i++) { ClsFile cf = sbList.get(i); String className = cf.getClassName(); StringBuffer str = cf.getContent(); // 处理classContent的"_" if ('_' == str.charAt(13)) { // 替换掉类名前缀的“_” str.replace(13, 14, ""); } // 处理className的"_" if ('_' == className.charAt(0)) { className = className.substring(1); } System.out.println("=========ClassName: " + className + "======================================" + i); System.out.println(str.toString()); writeClassFile(className, str.toString()); } } public final static ClsFile createClsHead(List
                              
                                sbList, String className) { ClsFile cf = new ClsFile(); cf.setClassName(className); cf.setContent(new StringBuffer(CLASS_HEAD_NAME + cf.getClassName() + FUHAO_1 + HUAN_HANG1)); sbList.add(cf); return cf; } public final static ClsFile createClsFoot(List
                               
                                 sbList, String className) { ClsFile cf = new ClsFile(); cf.setClassName(className); cf.setContent(new StringBuffer(FUHAO_2 + HUAN_HANG2)); sbList.add(cf); return cf; } public final static boolean alreadyHave(List
                                
                                  sbList, String className) { for (ClsFile cls : sbList) { if (className.equalsIgnoreCase(cls.getClassName())) { return true; } } return false; } public final static void creatFieldName(StringBuffer fieldNameBuilder, String fieldName, String fieldType) { fieldNameBuilder.append("private " + fieldType + " " + fieldName + HUAN_HANG2); } public final static void creatArrayFieldName(StringBuffer fieldNameBuilder, String fieldName, String fieldType) { fieldNameBuilder.append("private " + fieldType + "<" + fieldName + ">" + HUAN_HANG2); } /** * 创建类文件 * * @param className * @param content */ public final static void writeClassFile(String className, String content) { writeFile(FILE_PATH, className + ".java", content); } /** * 写入文件内容 * * @param path * @param tokenName * @param content */ public final static void writeFile(String path, String name, String content) { File file = new File(path + "/" + name); try { file.createNewFile(); FileOutputStream os = new FileOutputStream(file); OutputStreamWriter osWriter = new OutputStreamWriter(os); BufferedWriter buffWriter = new BufferedWriter(osWriter); buffWriter.write(content); buffWriter.flush(); buffWriter.close(); osWriter.close(); os.close(); } catch (IOException e) { e.printStackTrace(); } } // 读取文件 public static String readTxtFile(String filePath) { try { File file = new File(filePath); if (file.isFile() && file.exists()) { // 判断文件是否存在 InputStreamReader read = new InputStreamReader(new FileInputStream(file));// BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; StringBuffer str = new StringBuffer(); while ((lineTxt = bufferedReader.readLine()) != null) { str.append(lineTxt); } read.close(); return str.toString(); } else { System.out.println("找不到指定的文件"); } } catch (Exception e) { System.out.println("读取文件内容出错"); e.printStackTrace(); } return ""; } } class ClsFile { private String className; private StringBuffer content; public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public StringBuffer getContent() { return content; } public void setContent(StringBuffer content) { this.content = content; } @Override public String toString() { return "ClsFile [className=" + className + ", content=" + content + "]"; } }
                                
                               
                              
                             
                            
                           
                          
                         
                        
                       
                      
                     
                    
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
 
网友评论