Java实现读写文件功能的代码分享

目录

  • 读文件
  • 写文件
  • 主函数
  • 实现效果
下面是利用Java实现读写文件功能的示例代码

读文件 TextRead.java
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class TextRead {/*** 读取txt文件的内容* @param file 想要读取的文件对象* @return 返回文件内容*/public static String txt2String(File file){StringBuilder result = new StringBuilder(); try{BufferedReader br = new BufferedReader(new FileReader(file)); //构造一个BufferedReader类来读取文件String s = null; while((s = br.readLine())!=null){//使用readLine方法,一次读一行result.append(System.lineSeparator()+s); }br.close(); }catch(Exception e){e.printStackTrace(); }System.out.println("TextRead" + result.toString()); return result.toString(); } public static void main(String[] args){File file = new File("D:\\fileCreate\\2022_08_17_10_08_501.txt"); System.out.println(txt2String(file)); }}


写文件 WriteFile.java
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class WriteFile { public static void writeFileContent(String path, String MyStrs){ FileWriter fw=null; //文件路径String filePath = path; //日期格式SimpleDateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH_MM_SS"); SimpleDateFormat dfTime = new SimpleDateFormat("yyyy-MM-dd:HH:MM:SS"); String fileName=df.format(new Date())+".txt"; File newFile=new File(filePath); if(!newFile.exists()) {newFile.mkdir(); }File f=new File(filePath,fileName); try {//创建文件f.createNewFile(); fw=new FileWriter(f); //写入数据String poem = MyStrs; //System.out.println("WriteFile" + poem); fw.write(dfTime.format(new Date())+ poem); } catch (IOException e) {throw new RuntimeException("文件创建失败"); }finally {try {fw.close(); } catch (IOException e) {throw new RuntimeException("文件流关闭失败"); }}} public static void main(String[] strings){ String filePath="D:\\fileCreate"; String strs = "西北有高楼,上与浮云齐;" +"烟笼寒水月笼沙,夜泊秦淮近酒家;" +"商女不知亡国恨,隔江犹唱后庭花。" +"Hello world" +"1234567890"; WriteFile.writeFileContent(filePath, strs); System.out.println("WriteFile" + strs); }}


主函数 【Java实现读写文件功能的代码分享】Main.java
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class Main {public static void main(String[] args) { String filePath="D:\\fileCreate"; String strs = "西北有高楼,上与浮云齐;" +"烟笼寒水月笼沙,夜泊秦淮近酒家;" +"商女不知亡国恨,隔江犹唱后庭花。" +"Hello world" +"12345667890"; WriteFile.writeFileContent(filePath, strs); File file = new File("D:\\fileCreate\\2022_08_17_10_08_501.txt"); //String showFile = new String(); //showFile = TextRead.txt2String(file); //System.out.printf(showFile); //System.out.println(showFile); System.out.println("file = " + TextRead.txt2String(file)); System.out.println(TextRead.txt2String(file)); }}


实现效果 Java实现读写文件功能的代码分享
文章图片

Java实现读写文件功能的代码分享
文章图片

不知道为什么,writefile运行就出错了
Java实现读写文件功能的代码分享
文章图片

到此这篇关于Java实现读写文件功能的代码分享的文章就介绍到这了,更多相关Java读写文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读