今天的笔试题,小小的记录一下

package com.example.demo; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.io.*; import java.util.*; @SpringBootApplication public class DemoApplication { public static void main(String[] args) throws IOException { Map<Integer, String> read = readTxtFile("D:\\data\\list.txt"); final StringBuffer stringBuffer = new StringBuffer(); final Iterator<Integer> iterator = read.keySet().iterator();//keySet()返回值,所有key;iterator()遍历 //当在缓冲区内扫描到字符时,会返回true, 否则会发生阻塞,等待数据输入。 //hasNext("World")匹配到对应字符返回true, while (iterator.hasNext()){ Integer key = iterator.next(); String s = read.get(key); stringBuffer.append(s+" "); } String read1 = read(stringBuffer.toString()); writeTxtFile("D:\\data\\outputtxt",read1); } //冒泡排序 public static String read(String s){ List<String> strings = new ArrayList<>(1000); String[] split1 = s.split(" "); for (int i=0;i<split1.length-1;i++){ for (int j=0;j<split1.length-1;j++){ String temp=""; if (split1[j].length()>split1[j+1].length()){ temp=split1[j]; split1[j]=split1[j+1]; split1[j+1]=temp; } } } String split=Arrays.toString(split1); String substring = split.substring(1, split.length() - 1); return substring; } private static Map<Integer,String> readTxtFile(String filePath){ Map<Integer, String> txtMap = new HashMap<Integer,String>(1000);//<key,value> try(FileInputStream fileInputStream = new FileInputStream(filePath);//从文件系统中的某个文件中获得输入字节 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);//创建一个使用默认字符集的 InputStreamReader。字节转换为字符 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);)//缓存区 BufferReader类用来包装所有其 read() 操作可能开销很高的 Reader(如 FileReader 和InputStreamReader)。 { String line = null; Integer i = 0; while ((line =bufferedReader.readLine())!=null){//readline() 方法用于从文件读取整行,包括 “\n” 字符 i=i+1; txtMap.put(i,line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }return txtMap; } private static void writeTxtFile(String filePath,String textList)throws IOException{ final File file = new File(filePath);//通过给定的父抽象路径名和子路径名字符串创建一个新的File实例 file.createNewFile(); try(FileWriter fileWriter =new FileWriter(file);//字符向流中写入数据 final BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)){//BufferedWriter加入了缓冲技术,将字符读取对象作为参数 for (String text:textList.split(", ")){//循环textList赋值给text bufferedWriter.write(text);//text写入 bufferedWriter.newLine();//使用自己的行分隔符概念 } bufferedWriter.flush(); }catch (Exception e){ e.printStackTrace(); } } }
本文来自博客园,作者:阿霖找BUG,转载请注明原文链接:https://www.cnblogs.com/lin-07/p/17277994.html
浙公网安备 33010602011771号