FileReader
和FileWriter
分别是用于读写字符文件的便捷类。 FileReader
和FileWriter
类都使用系统的默认编码。
以下示例显示了FileReader
和FileWriter
的用法。
文件:FileReaderWriterExample.java –
package com.yiibai.tutorial.io; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * @author yiibai */ public class FileReaderWriterExample { public static void main(String[] args) { File file = new File("file.txt"); /* Writing File Using FileWriter */ FileWriter fileWriter = null; try { fileWriter = new FileWriter(file); fileWriter.write("This is an example of using"); fileWriter.write(" FileReader and "); fileWriter.write(" FileWriter. "); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileWriter != null) { fileWriter.close(); } } catch (Exception e) { e.printStackTrace(); } } /* Reading File Using FileReader */ FileReader fileReader = null; try { fileReader=new FileReader(file); char ch[]=new char[20]; int i=0; while((i=fileReader.read(ch))!=-1){ System.out.println(new String(ch,0,i)); } } catch (IOException e) { e.printStackTrace(); }finally { try { if (fileReader != null) { fileReader.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
执行上面示例代码,得到以下结果:
This is an example o f using FileReader a nd FileWriter.
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264107.html