Java读写文件

@Test
    void test(){
        String txtPath = "C:\\Users\\24634\\Desktop\\面试题.txt";
        File file = new File(txtPath);
        if(file.isFile() && file.exists()){
            try {
                //读文件
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                StringBuffer sb = new StringBuffer();
                String text = null;
                while((text = bufferedReader.readLine()) != null){
                    if (text.length() > 40){
                        sb.append(text.substring(0, 39));
                        sb.append("\n");
                        sb.append(text.substring(39));
                        sb.append("\n");
                    }else {
                        sb.append(text);
                        sb.append("\n");
                    }
                }
//                System.out.println(sb.toString());
                bufferedReader.close();
                
                //写文件,没有会自动创建
                File file1 = new File("D:\\面试题.txt");
//                file1.createNewFile();
                FileOutputStream fileOutputStream = new FileOutputStream(file1);
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
                BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
                bufferedWriter.write(sb.toString());
                bufferedWriter.flush();
                bufferedWriter.close();
//                return sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        return null;
    }

你可能感兴趣的:(java,面试,spring)