问题一我想优化下面这段代码问题二我在读取文件之前,先获取文件夹中文件的数量,然后根据文件的数量遍历文件,将文件转换成字符串//文件解析成字符串ClassLoaderclassLoader=TelecomThreeListener.class.getClassLoader();URLresource=classLoader.getResource("bauschData/selectData01.json");Stringpath=resource.getPath();//System.out.println(path);StringfileName01=path;resource=classLoader.getResource("bauschData/selectData02.json");path=resource.getPath();StringfileName02=path;resource=classLoader.getResource("bauschData/selectData03.json");path=resource.getPath();StringfileName03=path;//默认读取文件Filefile=newFile(fileName01);StringBuffersb=newStringBuffer();Stringline;BufferedReaderbr=null;//数据-无try{br=newBufferedReader(newFileReader(file));}catch(FileNotFoundExceptione){e.printStackTrace();}try{while((line=br.readLine())!=null){sb.append(line);}}catch(IOExceptione){e.printStackTrace();}Stringnothing=sb.toString();//数据-1file=newFile(fileName01);sb=newStringBuffer();try{br=newBufferedReader(newFileReader(file));}catch(FileNotFoundExceptione){e.printStackTrace();}try{while((line=br.readLine())!=null){sb.append(line);}}catch(IOExceptione){e.printStackTrace();}StringbauschDataJson01=sb.toString();//数据-2file=newFile(fileName02);sb=newStringBuffer();try{br=newBufferedReader(newFileReader(file));}catch(FileNotFoundExceptione){e.printStackTrace();}try{while((line=br.readLine())!=null){sb.append(line);}}catch(IOExceptione){e.printStackTrace();}StringbauschDataJson02=sb.toString();//数据-3file=newFile(fileName03);sb=newStringBuffer();try{br=newBufferedReader(newFileReader(file));}catch(FileNotFoundExceptione){e.printStackTrace();}try{while((line=br.readLine())!=null){sb.append(line);}}catch(IOExceptione){e.printStackTrace();}StringbauschDataJson03=sb.toString();
2 回答

慕桂英4014372
TA贡献1871条经验 获得超13个赞
问题一:从文件中读取数据的代码可以封装为一个单独的方法,例如:publicstaticStringreadFileAsString(StringfilePath)throwsIOException{returnreadFileAsString(newFile(filePath));}publicstaticStringreadFileAsString(Filefile)throwsIOException{try(BufferedReaderreader=newBufferedReader(newFileReader(file))){StringBuildercontent=newStringBuilder();for(Stringline;(line=reader.readLine())!=null;){content.append(line);}returncontent.toString();}}如果使用Java8,readFileAsString方法会更简单:publicstaticStringreadFileAsString(Filefile)throwsIOException{returnFiles.lines(file.toPath()).collect(Collectors.joining(""));}这样的话,你就不需要每次读取某个文件的时候,都写一堆逻辑同样的代码,而是直接调用readFileAsString方法就行。问题二:Java遍历某个目录的API很多,如果只是非递归遍历,即只列出当前目录的文件,可以使用:File类的listFiles方法Files类的list方法,返回Stream,从而可以使用Lambda表达式。

尚方宝剑之说
TA贡献1788条经验 获得超4个赞
Fileroot=newFile(App.class.getClassLoader().getResource("bauschData/").getPath());Arrays.stream(Objects.requireNonNull(root.listFiles())).filter(file->file.getName().endsWith("json")).map(File::toPath).forEach(path->{try{Listlines=Files.readAllLines(path); }catch(IOExceptione){e.printStackTrace();}});你要算一下所有文件的大小你内存放得下不,如果放不下那最好改成Scanner逐行扫描的方式去读。
添加回答
举报
0/150
提交
取消