项目中要求批量txt文件可以转换为java文件或xml文件,以下主要是总结的几种IO读写的方法;

   1、按行读写txt文件和java文件,以treemap默认升序的有序map类型保存读写的结果转换;

      

  1 package com.yss.util;
  2
  3 import java.io.BufferedReader;
  4 import java.io.BufferedWriter;
  5 import java.io.File;
  6 import java.io.FileInputStream;
  7 import java.io.FileNotFoundException;
  8 import java.io.FileOutputStream;
  9 import java.io.IOException;
 10 import java.io.InputStreamReader;
 11 import java.io.OutputStreamWriter;
 12 import java.util.Map;
 13 import java.util.TreeMap;
 14
 15 public class Test01 {
 16
 17     public static void main(String[] args) {
 18         try {
 19             readfile("C:\\知识\\yss");
 20         } catch (FileNotFoundException e) {
 21             // TODO Auto-generated catch block
 22             e.printStackTrace();
 23         } catch (IOException e) {
 24             // TODO Auto-generated catch block
 25             e.printStackTrace();
 26         }
 27
 28     }
 29
 30     /**
 31      * 删除单个文件
 32      *
 33      * @param fileName
 34      *            要删除的文件的文件名
 35      * @return 单个文件删除成功返回true,否则返回false
 36      */
 37     public static boolean deleteFile(String fileName) {
 38         File file = new File(fileName);
 39         // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
 40         if (file.exists() && file.isFile()) {
 41             if (file.delete()) {
 42                 System.out.println("删除单个文件" + fileName + "成功!");
 43                 return true;
 44             } else {
 45                 System.out.println("删除单个文件" + fileName + "失败!");
 46                 return false;
 47             }
 48         } else {
 49             System.out.println("删除单个文件失败:" + fileName + "不存在!");
 50             return false;
 51         }
 52     }
 53
 54     private static void duxie(String name01,String name02) {
 55         Map<Integer, String> map = new TreeMap<Integer, String>();
 56
 57         int i=0;
 58         /* 读取数据 */
 59         try {
 60             BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(name01)),
 61                                                                          "UTF-8"));
 62             String lineTxt = null;
 63
 64             while ((lineTxt = br.readLine()) != null) {
 65                 map.put(i, lineTxt);
 66                 i++;
 67             }
 68             br.close();
 69         } catch (Exception e) {
 70             System.err.println("read errors :" + e);
 71         }
 72         //创建一个文件
 73         File fileName=new File(name02);
 74         try{
 75             if(!fileName.exists()){
 76                 fileName.createNewFile();
 77             }
 78         }catch(Exception e){
 79             e.printStackTrace();
 80         }
 81         //删除掉原来的文件
 82         deleteFile(name01);
 83
 84         /* 输出数据 */
 85         try {
 86             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(name02)),
 87                                                                           "UTF-8"));
 88
 89             for (Integer ii : map.keySet()) {
 90                 bw.write(map.get(ii));
 91                 bw.newLine();
 92             }
 93             bw.close();
 94         } catch (Exception e) {
 95             System.err.println("write errors :" + e);
 96         }
 97
 98     }
 99
100     /**
101      * 读取某个文件夹下的所有文件
102      */
103     public static boolean readfile(String filepath) throws FileNotFoundException, IOException {
104         try {
105                 File file = new File(filepath);
106                 if (!file.isDirectory()) {
107                         System.out.println("文件");
108                         String path=file.getPath();
109                         System.out.println("name=" + file.getName());
110                         if(file.getName().indexOf("java")>0){
111                             String path01=file.getPath().replace(file.getName(), file.getName().replace("java", "txt"));
112                             System.out.println(file.getName().replace("java", "txt")+"复制以后文件路径:"+path01);
113                             duxie(path,path01);
114                         }
115
116                 } else if (file.isDirectory()) {
117                         System.out.println("文件夹");
118                         String[] filelist = file.list();
119                         for (int i = 0; i < filelist.length; i++) {
120                                 File readfile = new File(filepath + "\\" + filelist[i]);
121                                 if (!readfile.isDirectory()) {
122
123                                     String path=readfile.getPath();
124                                     System.out.println("name=" + readfile.getName());
125                                     if(readfile.getName().indexOf("java")>0){
126                                         String path01=readfile.getPath().replace(readfile.getName(), readfile.getName().replace("java", "txt"));
127                                         System.out.println(readfile.getName().replace("java", "txt")+"复制以后文件路径:"+path01);
128                                         duxie(path,path01);
129                                     }
130                                 } else if (readfile.isDirectory()) {
131                                         readfile(filepath + "\\" + filelist[i]);
132                                 }
133                         }
134
135                 }
136
137         } catch (FileNotFoundException e) {
138                 System.out.println("readfile()   Exception:" + e.getMessage());
139         }
140         return true;
141     }
142
143 }

2、关于普通的txt文件读写,创建,删除的简单方法;

  1 package com.yss.util;
  2
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileOutputStream;
  7 import java.io.FileWriter;
  8 import java.io.IOException;
  9 import java.io.InputStreamReader;
 10
 11 public class Test {
 12     /**
 13      * 创建文件
 14      * @param fileName
 15      * @return
 16      */
 17     public static boolean createFile(File fileName)throws Exception{
 18         try{
 19             if(!fileName.exists()){
 20                 fileName.createNewFile();
 21             }
 22         }catch(Exception e){
 23             e.printStackTrace();
 24         }
 25         return true;
 26     }
 27
 28
 29     /**
 30      *读取TXT内容
 31      * @param file
 32      * @return
 33      */
 34     public static String readTxtFile(File file){
 35         String result = "";
 36         try {
 37             InputStreamReader reader = new InputStreamReader(new FileInputStream(file),"gbk");
 38             BufferedReader br = new BufferedReader(reader);
 39             String s = null;
 40             while((s=br.readLine())!=null){
 41                 result = result  + s;
 42                 System.out.println(s);
 43             }
 44         } catch (Exception e) {
 45             e.printStackTrace();
 46         }
 47         return result;
 48     }
 49
 50
 51     /**
 52      * 写入TXT,覆盖原内容
 53      * @param content
 54      * @param fileName
 55      * @return
 56      * @throws Exception
 57      */
 58     public static boolean writeTxtFile(String content,File fileName)throws Exception{
 59         boolean flag=false;
 60         FileOutputStream fileOutputStream=null;
 61         try {
 62             fileOutputStream = new FileOutputStream(fileName);
 63             fileOutputStream.write(content.getBytes("gbk"));
 64             fileOutputStream.close();
 65             flag=true;
 66         } catch (Exception e) {
 67             e.printStackTrace();
 68         }
 69         return flag;
 70     }
 71
 72
 73     /**
 74      * 写入TXT,追加写入
 75      * @param filePath
 76      * @param content
 77      */
 78     public static void fileChaseFW(String filePath, String content) {
 79         try {
 80             //构造函数中的第二个参数true表示以追加形式写文件
 81             FileWriter fw = new FileWriter(filePath,true);
 82             fw.write(content);
 83             fw.close();
 84         } catch (IOException e) {
 85             System.out.println("文件写入失败!" + e);
 86         }
 87     }
 88
 89
 90
 91     public static void main(String[] args) throws Exception{
 92         File file = new File("C:\\知识\\123.txt");
 93         File file01 = new File("C:\\知识\\1234.txt");
 94         createFile(file01);
 95         //readTxtFile(file);
 96         writeTxtFile(readTxtFile(file)+"我是写入的内容11",file01);
 97         //fileChaseFW("C:\\知识\\1234.txt","66666666");
 98     }
 99
100 }

3、删除文件或文件夹,或此目录下的文件的java实现方法;

  1 package com.yss.util;
  2
  3 import java.io.File;
  4
  5 /**
  6  * 删除文件和目录
  7  *
  8  */
  9 public class Test03 {
 10
 11     /**
 12      * 删除文件,可以是文件或文件夹
 13      *
 14      * @param fileName
 15      *            要删除的文件名
 16      * @return 删除成功返回true,否则返回false
 17      */
 18     public static boolean delete(String fileName) {
 19         File file = new File(fileName);
 20         if (!file.exists()) {
 21             System.out.println("删除文件失败:" + fileName + "不存在!");
 22             return false;
 23         } else {
 24             if (file.isFile())
 25                 return deleteFile(fileName);
 26             else
 27                 return deleteDirectory(fileName);
 28         }
 29     }
 30
 31     /**
 32      * 删除单个文件
 33      *
 34      * @param fileName
 35      *            要删除的文件的文件名
 36      * @return 单个文件删除成功返回true,否则返回false
 37      */
 38     public static boolean deleteFile(String fileName) {
 39         File file = new File(fileName);
 40         // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
 41         if (file.exists() && file.isFile()) {
 42             if (file.delete()) {
 43                 System.out.println("删除单个文件" + fileName + "成功!");
 44                 return true;
 45             } else {
 46                 System.out.println("删除单个文件" + fileName + "失败!");
 47                 return false;
 48             }
 49         } else {
 50             System.out.println("删除单个文件失败:" + fileName + "不存在!");
 51             return false;
 52         }
 53     }
 54
 55     /**
 56      * 删除目录及目录下的文件
 57      *
 58      * @param dir
 59      *            要删除的目录的文件路径
 60      * @return 目录删除成功返回true,否则返回false
 61      */
 62     public static boolean deleteDirectory(String dir) {
 63         // 如果dir不以文件分隔符结尾,自动添加文件分隔符
 64         if (!dir.endsWith(File.separator))
 65             dir = dir + File.separator;
 66         File dirFile = new File(dir);
 67         // 如果dir对应的文件不存在,或者不是一个目录,则退出
 68         if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
 69             System.out.println("删除目录失败:" + dir + "不存在!");
 70             return false;
 71         }
 72         boolean flag = true;
 73         // 删除文件夹中的所有文件包括子目录
 74         File[] files = dirFile.listFiles();
 75         for (int i = 0; i < files.length; i++) {
 76             // 删除子文件
 77             if (files[i].isFile()) {
 78                 flag = Test03.deleteFile(files[i].getAbsolutePath());
 79                 if (!flag)
 80                     break;
 81             }
 82             // 删除子目录
 83             else if (files[i].isDirectory()) {
 84                 flag = Test03.deleteDirectory(files[i]
 85                         .getAbsolutePath());
 86                 if (!flag)
 87                     break;
 88             }
 89         }
 90         if (!flag) {
 91             System.out.println("删除目录失败!");
 92             return false;
 93         }
 94         // 删除当前目录
 95         if (dirFile.delete()) {
 96             System.out.println("删除目录" + dir + "成功!");
 97             return true;
 98         } else {
 99             return false;
100         }
101     }
102
103     public static void main(String[] args) {
104         String dir = "D:/home/web/upload/upload/files";
105         Test03.deleteDirectory(dir);
106
107     }
108
109 }

4、打印某目录下的文件名称和此文件的路径;

 1 package com.yss.util;
 2
 3 import java.io.File;
 4 import java.io.FileNotFoundException;
 5 import java.io.IOException;
 6
 7 public class Test02 {
 8       /**
 9      * 读取某个文件夹下的所有文件
10      */
11     public static boolean readfile(String filepath) throws FileNotFoundException, IOException {
12             try {
13                 File file = new File(filepath);
14                 if (!file.isDirectory()) {
15                         System.out.println("文件");
16                         System.out.println("path=" + file.getPath());
17                         System.out.println("name=" + file.getName());
18
19                 } else if (file.isDirectory()) {
20                         System.out.println("文件夹");
21                         String[] filelist = file.list();
22                         for (int i = 0; i < filelist.length; i++) {
23                                 File readfile = new File(filepath + "\\" + filelist[i]);
24                                 if (!readfile.isDirectory()) {
25                                         System.out.println("path=" + readfile.getPath());
26                                         System.out.println("absolutepath="
27                                                         + readfile.getAbsolutePath());
28                                         System.out.println("name=" + readfile.getName());
29
30                                 } else if (readfile.isDirectory()) {
31                                         readfile(filepath + "\\" + filelist[i]);
32                                 }
33                         }
34
35                 }
36
37         } catch (FileNotFoundException e) {
38                 System.out.println("readfile()   Exception:" + e.getMessage());
39         }
40         return true;
41     }
42
43     public static void main(String[] args) {
44         String l="Activator.java";
45         System.out.println(l.replace("java", "txt")+">>>>>>>>>>>");
46     }
47
48 }

以上的方法类都是相关的txt文件或java类型的文件的读写。

转载于:https://www.cnblogs.com/ananaini/p/9445605.html

java代码实现读写txt文件(txt文件转换成java文件)相关推荐

  1. html文件批量快速转换成JSP文件

    html文件批量快速转换成JSP文件 一.新建一个Web项目,把准备好的xxx.html(1个或多个)粘贴到项目的WebRoot文件夹或WebContent\WEB-INF\jsps文件夹(jsps这 ...

  2. java将office文档pdf文档转换成swf文件在线预览

    第一步,安装openoffice.org openoffice.org是一套sun的开源office办公套件,能在widows,linux,solaris等操作系统上执行. 主要模块有writer(文 ...

  3. PDF文件如何快速转换成Word文件?两个方法教你搞定

    PDF是一种广泛使用的文档格式,其被设计为与各种操作系统和软件平台兼容,使其成为在许多行业中共享文档的标准.但有时候,我们需要将PDF文档转换为Word文件,以方便编辑和修改.本文将介绍两种简单的方法 ...

  4. java代码二进制转为十六进制_Java 中二进制转换成十六进制的两种实现方法

    Java 中二进制转换成十六进制的两种实现方法 每个字节转成16进制,方法1 /** * 每个字节转成16进制,方法1 * * @param result */ private static Stri ...

  5. SAX 解析XML文件:将XML转换成Java对象

    本博客介绍的是解析本地XML文件,解析网络上的XML 本文写得比较简略,实际上项目应用更多的是解析网上的xml资源 使用SAX 处理XML需要一个Handler 对象,一般继承org.xml.sax, ...

  6. java将office文档,word,ppt,pdf文档转换成swf文件在线预览

    java将office文档pdf文档转换成swf文件在线预览 第一步,安装openoffice.org openoffice.org是一套sun的开源office办公套件,能在widows,linux ...

  7. tif文件转pdf_PPT怎么转换成PDF文件?可以帮到你的PPT转PDF方法

    PPT怎么转换成PDF文件?大家在平时的工作与学习中肯定接触且使用过PPT.PDF这两种格式的文件,随之就会有将PPT转换成PDF文件的需求.这是由于PPT文件兼容性比较差,不同设备打开文件的效果不同 ...

  8. 怎么把PDF转换成PPT文件?这两种方法一键转换

    PDF文件怎么能转换成PPT文件呢?大家在日常办公过程中,使用PDF文件来传输文件的次数居多,有时我们收到一份PDF文件,要求我们把它转换成PPT文件格式来用于会议展示,这时候我们如果对照着内容改成P ...

  9. python将txt转换为csv_Python Pandas 三行代码将 txt 文件转换成 csv 文件

    今天需要处理几个比较大的 txt 文件,每个文件都在 2GB 以上,直接用 Excel 将其转换成 csv 文件显然是不太可行的,于是用 Python 中的数据处理神器 Pandas,三行代码就能搞定 ...

  10. 利用MATLAB将图片转换成coe文件、TXT文件、mif文件、bin文件

    利用MATLAB将图片转换成coe文件.TXT文件.mif文件 利用MATLAB将图片转换成coe文件 利用MATLAB将图片转换成txt文件 利用MATLAB将图片转换成mif文件 利用MATLAB ...

最新文章

  1. 加拿大生信开源学习资源Bioinformatics.ca
  2. 控制台没有消息循环_【干货】思科设备报错消息汇总大全~
  3. 小学 学生学籍信息汇总及自动检查代码(Python)
  4. Logstash配置方法
  5. c# 读取写入excel单元格(包括对excel的一些基本操作)
  6. spearman相关系数 matlab,数学建模——相关系数(4)——斯皮尔曼相关系数(spearman)...
  7. 德阳计算机办公培训,德阳2017计算机办公软件培训
  8. html支付宝图标,支付宝小程序基础组件 图标·Icon
  9. 中文界面blend_Blend Modes v3.4 – unity混合模式插件
  10. 详解vue中数据传递(父传子、子传父、兄弟之间以及vuex)代码附上
  11. 读了下神书 Introduction to Linear Optimization
  12. 苹果手机换android,我从苹果手机换回了安卓手机,是怎样的体验呢?
  13. 【CSS】从熟悉到更熟悉
  14. Zabbix5.0监控CenterOS(RPM版)
  15. [Netty]pipeline(二)
  16. linux清除大文件命令,linux du df命令清除不要的大文件
  17. ARM-translation table walk
  18. 【机器学习笔记11】高斯混合模型(GMM)【上篇】原理与推导
  19. html5 canvas 画阿迪达斯logo,HTML5 Canvas笔记——HTML5 Canvas绘图绘制太极图
  20. android 按键映射文件,《android 的按键映射表》.doc

热门文章

  1. 解析多层list_基于laravel5.2进行中间件源码的解析
  2. python发送soap报文_python用http发送soap报文进行webservice接口调用
  3. Element Form表单布局(一行多列)
  4. mysql5.5备份数据库_mysql5.5数据库备份
  5. 2021牛客暑期多校训练营1, 签到题DFBG
  6. 【POJ3630】Phone List(字典树)
  7. VBScript脚本
  8. c++ 形参用指针 还是对象_Java 和 C/C++两大高手的对比
  9. 通风技术交底书范文_通风与空调工程风管安装安全技术交底
  10. Python入门-try-except-else-finally