java读写文件
package fileTest;import myPackage.*;//自己的一个包import java.io.IOException;public class FileReadWritTest { public static void main(String[] args)throws IOException { MyFileClass myfile=new MyFileClass(); String filepath="C://Users//xgpxg//Desktop";//文件路径 String filename="test.txt";//文件名 myfile.setFilePath(filepath);//set文件路径 myfile.setFileName(filename);//set文件名 //myfile.writeFile("Word");//写文件 myfile.readFile();//读文件 }}文件读写类的一个简单封装
package myPackage;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;/** * 自定义文件类 * @author xgpxg * */ public class MyFileClass { PRivate String filepath=null; private String filename=null; /** * 文件路径 * @param filepath * @return */ public String setFilePath(String filepath){ this.filepath=filepath; return this.filepath; } /** * 文件名 * @param filename * @return */ public String setFileName(String filename){ this.filename=filename; return this.filename; } /** * 创建文件 * @param filepath 文件路径 * @param filename 文件名称 * @throws IOException */ public void create() throws IOException{ File file=new File(filepath+"//"+filename); if(!file.exists()) file.createNewFile(); else System.out.println("文件已存在!"); } /** * 写文件(自动追加换行) * @param text 文件内容 * @throws IOException */ public void writeFile(String text) throws IOException{ FileWriter fw=new FileWriter(filepath+"//"+filename, true);//true 追加到文件尾 fw.write(text+"/n"); fw.flush();//刷新文件 fw.close(); } /** * 读取文件 * @param filepath 文件路径 * @param filename 文件名 * @throws IOException */ public void readFile() throws IOException{ BufferedReader br=new BufferedReader(new FileReader(filepath+"//"+filename)); while(br.ready()){ System.out.println(br.readLine()); } br.close(); }}新闻热点
疑难解答