设为首页 加入收藏

TOP

java file 文件操作 operate file of java (一)
2014-11-24 07:23:28 】 浏览:5625
Tags:java file 文件 操作 operate

java文件操作
1 package com.b510;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.FileWriter;
7 import java.io.InputStream;
8 import java.io.PrintWriter;
9
10 /**
11 *
12 * @author Hongten

13 *
14 * 文件的操作
15 *
16 *
17 *
18 *
19 */www.2cto.com
20 public class OperateFiles {
21
22 /**
23 * @param args
24 */
25 public static void main(String[] args) {
26 OperateFiles operateFiles = new OperateFiles();
27 //新建一个文件夹
28 operateFiles.newFolder("c:/hongten");
29 //新建一个文件,同时向里面写入内容
30 operateFiles.newFile("c:/hongten/Hello.txt", "hello,i'm Hongten.你好");
31 //删除一个文件
32 operateFiles.deleteFile("c:/hongten/Hello.txt");
33 //删除一个文件夹
34 operateFiles.deleteFolder("c:/hongten");
35 //复制文件夹
36 operateFiles.copyFolder("c:/hongten", "e:/hongten");
37 //提取文件的扩展名
38 String expandedName=operateFiles.getExpandedName("c:/hongten/Hello.txt");
39 System.out.println(expandedName);
40 //提取文件的路径
41 System.out.println(operateFiles.getFilePath("c:/hongten/Hello.txt"));
42 }
43
44 /**
45 * 获得文件的扩展名
46 * @param filePath 文件的路径 如:c:/hongten/Hello.txt
47 * @return 文件的扩展名 如:txt
48 */
49 public String getExpandedName(String filePath){
50 return filePath.substring(filePath.lastIndexOf(".")+1);
51 }
52 /**
53 * 获得文件的路径
54 * @param file 文件的路径
55 * @return 文件的路径
56 */
57 public String getFilePath(String file){
58 return file.substring(0,file.lastIndexOf("/"));
59 }
60 /**
61 * 新建一个目录
62 *
63 * @param folderPath
64 * 新建目录的路径 如:c:\\newFolder
65 */
66 public void newFolder(String folderPath) {
67 try {
68 File myFolderPath = new File(folderPath.toString());
69 if (!myFolderPath.exists()) {
70 myFolderPath.mkdir();
71 }
72 } catch (Exception e) {
73 System.out.println("新建目录操作出错");
74 e.printStackTrace();
75 }
76 }
77
78 /**
79 * 新建一个文件
80 *
81 * @param filePath
82 * 新建文件的目录 如:c:\\hongten.java
83 */
84 public void newFile(String filePath) {
85 try {
86 File myFilePathFile = new File(filePath.toString());
87 if (!myFilePathFile.exists()) {
88 myFilePathFile.createNewFile();
89 }
90 } catch (Exception e) {
91 System.out.println("新文件创建失败");
92 e.printStackTrace();
93 }
94 }
95
96 /**
97 * 新建一个文件,同时向文件中写入内容
98 *
99 * @param filePath
100 * 新建文件的目录 如:c:\\hongten.java
101 * @param fileContent
102 * 向文件中写入的内容
103 */
104 public void newFile(String filePath, String fileContent) {
105 try {
106 newFile(filePath);
107 FileWriter resultFile = new FileWriter(filePath);
108 PrintWriter myFile = new PrintWriter(resultFile);
109 myFile.println(fileContent);
110 resultFile.close();
111 } catch (Exception e) {
112 System.o

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇三步学会Java Socket编程(三) 下一篇Java equals()和hashCode()的作用

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目