本文共33个字,预计阅读时间需要1分钟。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | package com.java.file; import jdk.nashorn.internal.ir.WhileNode; import java.io.*; /** * @author iBoy * @date 2019-07-11-22:37 */ //文件读取的一般步骤是 //1-创建文件的输入流fis,参数是文件对象 //2-创建文件输入流的reader //3-创建带有缓冲的输出reader public class ReadWriteFile { public static void main(String[] args) { File file=new File("test.txt"); if(file.exists()){ System.out.println("文件存在"); try {//文件输入的三个流 FileInputStream fis=new FileInputStream(file);//获取文件输入流,是字节流 InputStreamReader isr=new InputStreamReader(fis,"UTF-8");//是字符流,要制定编码,不然会乱码 BufferedReader br=new BufferedReader(isr);//带有缓冲的reader,可直接读取一行reader String line; try { while ((line=br.readLine())!=null){//如果这行数据不为空,输出文件内容 System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } //文件读取完成之后需要关闭输入流 //先打开的先关闭,后打开的后关闭 try { br.close(); isr.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } File newfile=new File("txt.txt");// if(newfile.exists()){ System.err.println("文件存在"); } else{ System.err.println("文件不存在"); try { newfile.createNewFile(); System.out.println("文件不存在但是文件创建成功"); } catch (IOException e) { e.printStackTrace(); System.err.println("文件创建失败"); } } try { FileOutputStream fos=new FileOutputStream(newfile);//如果不存在,会自动创建文件 OutputStreamWriter osw=new OutputStreamWriter(fos,"UTF-8"); BufferedWriter bw= new BufferedWriter(osw); try {//文件的写入具有覆盖性 bw.write("额额\n"); bw.write("2额额\n"); bw.write("1212\n"); bw.close(); osw.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } |

iBoy博客 微信公众号
请大佬们关注订阅iBoy博客微信公众号, 扫一扫关注,从此不迷路。 不定时放出付费资源、福利、推送更新等...
本文来自:iBoy博客 » 《Java入门—-文件的读写》
本文地址:https://iboy.tech/1780.html»英雄不问来路,转载请注明出处,(づ ̄ 3 ̄)づ
有话想说:那就赶紧去底部给我留言吧!
版权申明:本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 未本地化版本许可协议进行许可。