Java 创建文件夹和文件,字符串写入文件,读取文件

两个函数如下:

TextToFile(..)函数:将字符串写入给定文本文件;
createDir(..)函数:创建一个文件夹,有判别是否存在的功能。

 

 1  public void TextToFile(final String strFilename, final String strBuffer)  
 2       {  
 3         try  
 4         {      
 5           // 创建文件对象  
 6           File fileText = new File(strFilename);  
 7           // 向文件写入对象写入信息  
 8           FileWriter fileWriter = new FileWriter(fileText);  
 9       
10           // 写文件        
11           fileWriter.write(strBuffer);  
12           // 关闭  
13           fileWriter.close();  
14         }  
15         catch (IOException e)  
16         {  
17           //  
18           e.printStackTrace();  
19         }  
20       } 
21        public static boolean createDir(String destDirName) {  
22             File dir = new File(destDirName);  
23             if (dir.exists()) {  
24                 System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");  
25                 return false;  
26             }  
27             if (!destDirName.endsWith(File.separator)) {  
28                 destDirName = destDirName + File.separator;  
29             }  
30             //创建目录  
31             if (dir.mkdirs()) {  
32                 System.out.println("创建目录" + destDirName + "成功!");  
33                 return true;  
34             } else {  
35                 System.out.println("创建目录" + destDirName + "失败!");  
36                 return false;  
37             }  
38         } 

 

 1 /**
 2          * 功能:Java读取txt文件的内容
 3          * 步骤:1:先获得文件句柄
 4          * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
 5          * 3:读取到输入流后,需要读取生成字节流
 6          * 4:一行一行的输出。readline()。
 7          * 备注:需要考虑的是异常情况
 8          * @param filePath
 9          */
10         public static void readTxtFile(String filePath){
11             try {
12                     String encoding="utf-8";
13                     File file=new File(filePath);
14                     if(file.isFile() && file.exists()){ //判断文件是否存在
15                         InputStreamReader read = new InputStreamReader(
16                         new FileInputStream(file),encoding);//考虑到编码格式
17                         BufferedReader bufferedReader = new BufferedReader(read);
18                         String lineTxt = null;
19                         while((lineTxt = bufferedReader.readLine()) != null){
20                             System.out.println(lineTxt);
21                         }
22                         read.close();
23             }else{
24                 System.out.println("找不到指定的文件");
25             }
26             } catch (Exception e) {
27                 System.out.println("读取文件内容出错");
28                 e.printStackTrace();
29             }
30          
31         }

 

posted @ 2016-12-30 14:49  日月心诚  阅读(10212)  评论(0编辑  收藏  举报