生活大爆炸9季百度云 1-11季 高清百度云

Java7中那些新特性 - 4 (文件操作篇) - evil850209 - ITeye技术网站
博客分类:
& 以前两篇博客都是关于文件路径和文件信息,今天我们来看看Java7中提供了哪些新的API,可以让我们非常简单的复制、移动和删除文件以及路径。
& 首先来说如何创建一个新的文件夹和文件,直接上例子。
public static void main(String[] args) {
Path directoryPath = Paths.get("D:/home/sample");
Files.createDirectory(directoryPath);
System.out.println("Directory created successfully!");
Path filePath = Paths.get("D:/home/sample/test.txt");
Files.createFile(filePath);
System.out.println("File created successfully!");
Path directoriesPath = Paths.get("D:/home/sample/subtest/subsubtest");
System.out.println("Sub-directory created successfully!");
Files.createDirectories(directoriesPath);
} catch (FileAlreadyExistsException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
& 上例中,在调用createFile方法时,如果想要创建的文件已经存在,FileAlreadyExistsException会被抛出。createFile和createDirectory这个两个方法都是原子性的,即要不整个操作都能成功或者整个操作都失败。
& 复制一个文件同样非常简单,Files的copy方法就可以实现。在复制文件时,我们可以对复制操作加一个参数来指明具体如何进行复制。java.lang.enum.StandardCopyOption这个枚举可以用作参数传递给copy方法。
ATOMIC_MOVE 原子性的复制COPY_ATTRIBUTES 将源文件的文件属性信息复制到目标文件中REPLACE_EXISTING 替换已存在的文件
public static void main(String[] args) {
Path newFile = Paths.get("D:/home/sample/newFile.txt");
Path copiedFile = Paths.get("D:/home/sample/copiedFile.txt");
Files.createFile(newFile);
System.out.println("File created successfully!");
Files.copy(newFile, copiedFile, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied successfully!");
} catch (IOException e) {
e.printStackTrace();
& 此外copy方法还支持输入输出流作为参数,以来复制非文件系统的信息。而复制文件夹的操作也并不复杂,如下例。
public static void main(String[] args) {
Path originalDirectory = Paths.get("D:/home/sample");
Path newDirectory = Paths.get("D:/home/sample/tmp");
Files.copy(originalDirectory, newDirectory);
System.out.println("Directory copied successfully!");
} catch (IOException e) {
e.printStackTrace();
public static void main(String[] args) {
Path newFile = Paths.get("D:/home/sample/java7WebSite.html");
URI url = URI.create("http://jdk7.java.net/");
try (InputStream inputStream = url.toURL().openStream()) {
Files.copy(inputStream, newFile);
System.out.println("Site copied successfully!");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
& 在我们做开发工作的时候,有时需要用到一个临时文件做介质,这些临时文件不需要被持久的保存下来,当程序结束或者一个方法处理完,就可以被删除掉了。Java7中提供了对临时文件良好的操作方法。
public static void main(String[] args) {
Path rootDirectory = Paths.get("D:/home/sample");
Path tempDirectory = Files.createTempDirectory(rootDirectory, "");
System.out.println("Temporary directory created successfully!");
String dirPath = tempDirectory.toString();
System.out.println(dirPath);
Path tempFile = Files.createTempFile(tempDirectory, "", "");
System.out.println("Temporary file created successfully!");
String filePath = tempFile.toString();
System.out.println(filePath);
} catch (IOException e) {
e.printStackTrace();
& 我们可以通过给createTempDirectory和createTempFile方法传递不同的参数来指定临时文件的前缀和后缀,具体使用方式请参照JDK文档。
& Files类还提供了一些方法,方便我们修改那些文件本身和时间相关的属性。
public static void main(String[] args) {
Path path = Paths.get("D:/home/projects/note.txt");
BasicFileAttributeView view = Files.getFileAttributeView(path, BasicFileAttributeView.class);
FileTime lastModifiedT
FileTime lastAccessT
FileTime createT
BasicFileAttributes attributes = view.readAttributes();
lastModifiedTime = attributes.lastModifiedTime();
createTime = attributes.creationTime();
long currentTime = Calendar.getInstance().getTimeInMillis();
lastAccessTime = FileTime.fromMillis(currentTime);
view.setTimes(lastModifiedTime, lastAccessTime, createTime);
System.out.println(attributes.lastAccessTime());
Files.setLastModifiedTime(path, lastModifiedTime);
System.out.println(Files.getLastModifiedTime(path));
} catch (IOException e) {
e.printStackTrace();
& 当要修改文件所属用户的时候,运行Java程序的用户需要有特定的权限,这里对不同操作系统的权限控制方式不做介绍,大家可以自己学习一下。下例中的用户JavaUser必须是存在在系统中的,否则会抛UserPrincipalNotFoundException异常。
public static void main(String[] args) {
Path path = Paths.get("D:/home/projects/note.txt");
UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
UserPrincipal userPrincipal = lookupService.lookupPrincipalByName("JavaUser");
Files.setOwner(path, userPrincipal);
System.out.println("Owner: " + Files.getOwner(path));
} catch (IOException e) {
e.printStackTrace();
& 移动文件有一些地方需要注意,首先是如果移动一个文件夹,文件夹和其子文件夹都会被移动,跨磁盘移动的文件夹时,目标文件夹必须是空的,否则会有DirectoryNotEmptyException异常抛出。
&
& 如果我们移动文件的时候使用了StandardCopyOption.ATOMIC_MOVE选项,其他所有选项就都会被忽略,并且如果目标文件已经存在,老文件既不会被替换也不会有IOException异常抛出,结果和具体的系统实现有关。如果移动文件不能被原子性的完成,AtomicMoveNotSupportedException异常会被抛出。
public static void main(String[] args) {
Path sourceFile = Paths.get("D:/home/projects/note.txt");
Path destinationFile = Paths.get("D:/home/sample/note.txt");
Files.move(sourceFile, destinationFile, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File moved successfully!");
} catch (IOException e) {
e.printStackTrace();
& 删除文件可以使用Files的delete和deleteIfExists这两个方法。顾名思义,当文件不存在时deleteIfExists的删除结果为false。如果要删除一个文件夹,文件夹必须是空的,或者结合使用SimpleFileVisitor来将文件夹下所有内容都删除。
public static void main(String[] args) {
Path sourceFile = Paths.get("D:/home/projects/note_bak1.txt");
boolean result = Files.deleteIfExists(sourceFile);
if (result) {
System.out.println("File deleted successfully!");
sourceFile = Paths.get("D:/home/projects/note_bak2.txt");
Files.delete(sourceFile);
System.out.println("File deleted successfully!");
} catch (NoSuchFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
& 至此我们可以看到,Java7中复制删除或移动文件还是比较简单的,避免了之前过于复杂的API,而且大部分功能都是通过Files的静态方法实现的,对于我们使用非常方便。但文件的操作涉及到具体不同的操作系统是对文件的管理方式,因此我们还要对操作系统有一定的了解并正确使用不同的操作参数,才能更好的运用Java7中提供的这些API。
evil850209
浏览: 56625 次
来自: 天津
传说中的zhuangbility?
刚毕业的学生不适合做对日外包。over
evil850209 写道为什么说我是东软的?
那就是中软的? ...
深有同感,沉不下心!
为什么说我是东软的?用递归怎么循环创建文件夹_java吧_百度贴吧
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&签到排名:今日本吧第个签到,本吧因你更精彩,明天继续来努力!
本吧签到人数:0成为超级会员,使用一键签到本月漏签0次!成为超级会员,赠送8张补签卡连续签到:天&&累计签到:天超级会员单次开通12个月以上,赠送连续签到卡3张
关注:605,035贴子:
用递归怎么循环创建文件夹收藏
文件夹名从A到Z
每个文件夹里面又有A到Z的文件夹
以此类推。。。
for循环做过
每多一级子目录
循环嵌套就要多一层
java培训---美国上市公司出品,入学签订就业协议,名企疯抢达内学员.java,O基础小班授课,java专家领衔授课,免费试听,满意后付款!
登录百度帐号推荐应用
为兴趣而生,贴吧更懂你。或Java读写文件创建文件夹多种方法示例详解
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了Java读写文件创建文件夹等多种操作的方法,大家参考使用吧
出现乱码请修改为
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "GBK"));
一.获得控制台用户输入的信息
代码如下:public String getInputMessage() throws IOException...{&&&&System.out.println("请输入您的命令∶");&&&&byte buffer[]=new byte[1024];&&&&int count=System.in.read(buffer);&&&&char[] ch=new char[count-2];//最后两位为结束符,删去不要&&&&for(int i=0;i&count-2;i++)&&&&&&&&ch[i]=(char)buffer[i];&&&&String str=new String(ch);&&&&}
可以返回用户输入的信息,不足之处在于不支持中文输入,有待进一步改进。
二.复制文件
1.以文件流的方式复制文件
代码如下:public void copyFile(String src,String dest) throws IOException...{&&&&FileInputStream in=new FileInputStream(src);&&&&File file=new File(dest);&&&&if(!file.exists())&&&&&&&&file.createNewFile();&&&&FileOutputStream out=new FileOutputStream(file);&&&&&&&&byte buffer[]=new byte[1024];&&&&while((c=in.read(buffer))!=-1)...{&&&&&&&&for(int i=0;i&c;i++)&&&&&&&&&&&&out.write(buffer[i]);&&&&&&& &&&&}&&&&in.close();&&&&out.close();}
该方法经过测试,支持中文处理,并且可以复制多种类型,比如txt,xml,jpg,doc等多种格式
1.利用PrintStream写文件
代码如下:public void PrintStreamDemo()...{&&&&try ...{&&&&&&&&FileOutputStream out=new FileOutputStream("D:/test.txt");&&&&&&&&PrintStream p=new PrintStream(out);&&&&&&&&for(int i=0;i&10;i++)&&&&&&&&&&&&p.println("This is "+i+" line");&&&&} catch (FileNotFoundException e) ...{&&&&&&&&e.printStackTrace();&&&&}}
2.利用StringBuffer写文件
代码如下:public void StringBufferDemo() throws IOException......{&&&&&&&&&File file=new File("/root/sms.log");&&&&&&&&&if(!file.exists())&&&&&&&&&&&&&file.createNewFile();&&&&&&&&&FileOutputStream out=new FileOutputStream(file,true);&&&&&&& &&&&&&&&&for(int i=0;i&10000;i++)......{&&&&&&&&&&&&&StringBuffer sb=new StringBuffer();&&&&&&&&&&&&&sb.append("这是第"+i+"行:前面介绍的各种方法都不关用,为什么总是奇怪的问题 ");&&&&&&&&&&&&&out.write(sb.toString().getBytes("utf-8"));&&&&&&&&&}&&&&&&& &&&&&&&&&out.close();&&&&&}
该方法可以设定使用何种编码,有效解决中文问题。
四.文件重命名
代码如下:public void renameFile(String path,String oldname,String newname)...{&&&&if(!oldname.equals(newname))...{//新的文件名和以前文件名不同时,才有必要进行重命名&&&&&&&&File oldfile=new File(path+"/"+oldname);&&&&&&&&File newfile=new File(path+"/"+newname);&&&&&&&&if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名&&&&&&&&&&&&System.out.println(newname+"已经存在!");&&&&&&&&else...{&&&&&&&&&&&&oldfile.renameTo(newfile);&&&&&&&&}&&&&}&&&&&&&& }
五.转移文件目录
转移文件目录不等同于复制文件,复制文件是复制后两个目录都存在该文件,而转移文件目录则是转移后,只有新目录中存在该文件。
代码如下:public void changeDirectory(String filename,String oldpath,String newpath,boolean cover)...{&&&&if(!oldpath.equals(newpath))...{&&&&&&&&File oldfile=new File(oldpath+"/"+filename);&&&&&&&&File newfile=new File(newpath+"/"+filename);&&&&&&&&if(newfile.exists())...{//若在待转移目录下,已经存在待转移文件&&&&&&&&&&&&if(cover)//覆盖&&&&&&&&&&&&&&&&oldfile.renameTo(newfile);&&&&&&&&&&&&else&&&&&&&&&&&&&&&&System.out.println("在新目录下已经存在:"+filename);&&&&&&&&}&&&&&&&&else...{&&&&&&&&&&&&oldfile.renameTo(newfile);&&&&&&&&}&&&&}&&&&&& }
1.利用FileInputStream读取文件
代码如下:public String FileInputStreamDemo(String path) throws IOException...{&&&&&&&&&File file=new File(path);&&&&&&&&&if(!file.exists()||file.isDirectory())&&&&&&&&&&&&&throw new FileNotFoundException();&&&&&&&&&FileInputStream fis=new FileInputStream(file);&&&&&&&&&byte[] buf = new byte[1024];&&&&&&&&&StringBuffer sb=new StringBuffer();&&&&&&&&&while((fis.read(buf))!=-1)...{&&&&&&&&&&&&&sb.append(new String(buf));&&& &&&&&&&&&&&&&buf=new byte[1024];//重新生成,避免和上次读取的数据重复&&&&&&&&&}&&&&&&&&&return sb.toString();&&&&&}
2.利用BufferedReader读取
在IO操作,利用BufferedReader和BufferedWriter效率会更高一点
代码如下:public String BufferedReaderDemo(String path) throws IOException...{&&&&File file=new File(path);&&&&if(!file.exists()||file.isDirectory())&&&&&&&&throw new FileNotFoundException();&&&&BufferedReader br=new BufferedReader(new FileReader(file));&&&&String temp=&&&&StringBuffer sb=new StringBuffer();&&&&temp=br.readLine();&&&&while(temp!=null)...{&&&&&&&&sb.append(temp+" ");&&&&&&&&temp=br.readLine();&&&&}&&&&return sb.toString();}
3.利用dom4j读取xml文件
代码如下:public Document readXml(String path) throws DocumentException, IOException...{&&&&File file=new File(path);&&&&BufferedReader bufferedreader = new BufferedReader(new FileReader(file));&&&&SAXReader saxreader = new SAXReader();&&&&Document document = (Document)saxreader.read(bufferedreader);&&&&bufferedreader.close();&&&&}
七.创建文件(文件夹)
1.创建文件夹&
代码如下:public void createDir(String path){&&&&&&&&&File dir=new File(path);&&&&&&&&&if(!dir.exists())&&&&&&&&&&&&&dir.mkdir();&&&&&}&
2.创建新文件
代码如下:public void createFile(String path,String filename) throws IOException{&&&&&&&&&File file=new File(path+"/"+filename);&&&&&&&&&if(!file.exists())&&&&&&&&&&&&&file.createNewFile();&&&&&}
八.删除文件(目录)
1.删除文件&&&
代码如下:public void delFile(String path,String filename){&&&&&&&&&File file=new File(path+"/"+filename);&&&&&&&&&if(file.exists()&&file.isFile())&&&&&&&&&&&&&file.delete();&&&&&}
2.删除目录要利用File类的delete()方法删除目录时,必须保证该目录下没有文件或者子目录,否则删除失败,因此在实际应用中,我们要删除目录,必须利用递归删除该目录下的所有子目录和文件,然后再删除该目录。
代码如下:public void delDir(String path)...{&&&&File dir=new File(path);&&&&if(dir.exists())...{&&&&&&&&File[] tmp=dir.listFiles();&&&&&&&&for(int i=0;i&tmp.i++)...{&&&&&&&&&&&&if(tmp[i].isDirectory())...{&&&&&&&&&&&&&&&&delDir(path+"/"+tmp[i].getName());&&&&&&&&&&&&}&&&&&&&&&&&&else...{&&&&&&&&&&&&&&&&tmp[i].delete();&&&&&&&&&&&&}&&&&&&&&}&&&&&&&&dir.delete();&&&&}}
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具Java创建文件且写入内容的方法
作者:夕橘子
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了Java创建文件且写入内容的方法的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
前两天在项目中因为要通过http请求获取一个比较大的json数据(300KB左右)并且保存,思来想去,最后还是决定将获取到的json数据以文件的形式保存下来,每次使用的时候去读取文件就可以了。
废话不多说了,直接上代码。
以下是代码截图,文章结尾会有完成的代码文件可供下载。
创建文件方法:
写入文件内容方法:
删除文件方法:
关于文件创建,写入内容,删除。可以根据自己的情况再稍作修改。
以下是代码类。
package com.file.
import java.io.BufferedR
import java.io.F
import java.io.FileInputS
import java.io.FileOutputS
import java.io.IOE
import java.io.InputStreamR
import java.io.PrintW
import java.util.UUID;
* @author 夕橘子-O
* @version 日 上午10:38:49
public class ForFile {
//生成文件路径
private static String path = "D:\\file\\";
//文件路径+名称
private static String filenameT
* 创建文件
* @param fileName 文件名称
* @param filecontent 文件内容
* @return 是否创建成功,成功则返回true
public static boolean createFile(String fileName,String filecontent){
Boolean bool =
filenameTemp = path+fileName+".txt";//文件路径+名称+文件类型
File file = new File(filenameTemp);
//如果文件不存在,则创建新的文件
if(!file.exists()){
file.createNewFile();
System.out.println("success create file,the file is "+filenameTemp);
//创建文件成功后,写入内容到文件里
writeFileContent(filenameTemp, filecontent);
} catch (Exception e) {
e.printStackTrace();
* 向文件中写入内容
* @param filepath 文件路径与名称
* @param newstr 写入的内容
* @throws IOException
public static boolean writeFileContent(String filepath,String newstr) throws IOException{
Boolean bool =
String filein = newstr+"\r\n";//新写入的行,换行
String temp = "";
FileInputStream fis =
InputStreamReader isr =
BufferedReader br =
FileOutputStream fos =
PrintWriter pw =
File file = new File(filepath);//文件路径(包括文件名称)
//将文件读入输入流
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buffer = new StringBuffer();
//文件原有内容
for(int i=0;(temp =br.readLine())!=i++){
buffer.append(temp);
// 行与行之间的分隔符 相当于“\n”
buffer = buffer.append(System.getProperty("line.separator"));
buffer.append(filein);
fos = new FileOutputStream(file);
pw = new PrintWriter(fos);
pw.write(buffer.toString().toCharArray());
pw.flush();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
//不要忘记关闭
if (pw != null) {
pw.close();
if (fos != null) {
fos.close();
if (br != null) {
br.close();
if (isr != null) {
isr.close();
if (fis != null) {
fis.close();
* 删除文件
* @param fileName 文件名称
public static boolean delFile(String fileName){
Boolean bool =
filenameTemp = path+fileName+".txt";
File file = new File(filenameTemp);
if(file.exists()){
file.delete();
} catch (Exception e) {
// TODO: handle exception
public static void main(String[] args) {
UUID uuid = UUID.randomUUID();
createFile(uuid+"myfile", "我的梦说别停留等待,就让光芒折射泪湿的瞳孔,映出心中最想拥有的彩虹,带我奔向那片有你的天空,因为你是我的梦 我的梦");
以上所述是小编给大家介绍的Java创建文件且写入内容的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具}

我要回帖

更多关于 生活大爆炸10季百度云 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信