对txt类文件的操作(外加)

字符流入文件(解决中文乱码问题)

File file=new File(road);
        try {
            FileWriter fileWriter = new FileWriter(file,true);//true代表写入文件不覆盖原文件
            BufferedWriter bufferedWriter=new BufferedWriter(fileWriter);
            String cin=scanner.nextLine();
            byte[] b=cin.getBytes();
            bufferedWriter.newLine();
            bufferedWriter.write(cin);

            bufferedWriter.close();//先关闭流
            fileWriter.close();//再关闭文件
        } catch (IOException e) {
            e.printStackTrace();
        }

读文件(解决中文乱码问题)

        try {

            FileInputStream fileInputStream=new FileInputStream(file);
            InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream, "GBK");//eclipse是utf-8,idea是GBK,别问,我也不知道为嘛
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            String line=null;
            while((line=bufferedReader.readLine())!=null){
                System.out.println(line);
            }
            bufferedReader.close();
            inputStreamReader.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

 

posted @ 2023-03-31 21:10  子过杨梅  阅读(18)  评论(0编辑  收藏  举报