文件

1、什么是文件?

文件是我们保存数据的地方。

2、文件流

文件在程序中是以流的形式来操作的。

流:数据在数据源(文件)和程序(内存)之间经历的路径

输入流:数据从数据源(文件)到程序(内存)的路径

输出流:数据从程序(内存)到数据源(文件)的路径

3、常用的文件操作

1、创建文件对象相关构造器和方法

new File(String pathname) //根据路径构建一个File对象

new File(File parent,String child) //根据父目录文件+子路径构建

new File(String parent,String child) //根据父目录+子路径构建

 

createNewFile() //创建文件

 

import org.testng.annotations.Test;

 

import java.io.File;

import java.io.IOException;

 

public class FileCreate {

    public static void main(String[] args) {

 

    }

    //方式1

 1 @Test
 2 
 3     public void create1(){
 4 
 5         String filePath = "D:\\file1.txt";
 6 
 7         File file = new File(filePath);
 8 
 9  
10 
11         try {
12 
13             file.createNewFile();
14 
15             System.out.println("创建文件1成功");
16 
17         } catch (IOException e) {
18 
19             e.printStackTrace();
20 
21         }
22 
23  
24 
25     }

  结果:

 

 

 

    //方式2

    

 1 @Test
 2     public void create2(){
 3 
 4         File parentFile = new File("D:\\");
 5 
 6         String fileNane = "file2.txt";
 7 
 8         File file = new File(parentFile, fileNane);
 9 
10 
11 
12         try {
13 
14             file.createNewFile();
15 
16             System.out.println("文件2创建成功");
17 
18         } catch (IOException e) {
19 
20             throw new RuntimeException(e);
21 
22         }
23 
24 
25 
26     }

    结果:

   

 

 

 

 

    //方式三

    

 1 @Test
 2     public void create3(){
 3 
 4         String parentPath = "d:\\";
 5 
 6         String filePath = "file3.txt";
 7 
 8         File file = new File(parentPath, filePath);
 9 
10         try {
11             file.createNewFile();
12             System.out.println("文件3创建成功");
13         } catch (IOException e) {
14             throw new RuntimeException(e);
15         }
16 
17     }

  结果:

 

 

 

2、获取文件的相关信息

常见的File相关方法

getName()/getAbsolutePath/getParent/length/exists/isFile/isDirectory

获取文件名、获取绝对路径

UTF-8一个英文一个字节,一个汉字三个字节

import org.testng.annotations.Test;

 

import java.io.File;

 

public class FileInformation {

    public static void main(String[] args) {

 

    }

 

    //获取文件信息

    

 1 @Test
 2     public void Info(){
 3         //先创建文件对象
 4         File file = new File("D:\\file1.txt");
 5         //调用相应方法,得到对应信息
 6         System.out.println("文件名称:"+file.getName());
 7 
 8         System.out.println("文件绝对路径:"+file.getAbsolutePath());
 9 
10         System.out.println("文件父目录:"+file.getParent());
11 
12         System.out.println("文件大小(字节):"+file.length());
13 
14         System.out.println("文件是否存在:"+file.exists());
15 
16         System.out.println("是否是文件:"+file.isFile());
17 
18         System.out.println("是否是目录:"+file.isDirectory());
19 
20     }

     结果:

 

 

 

3、目录的操作

创建一级目录:mkdir,创建多级目录:mkdirs  ,delete删除空目录或者文件

import org.testng.annotations.Test;

 

import java.io.*;

 

public class fileDirectory {

    public static void main(String[] args) {

 

    }

 

    //删除文件

    

 1 @Test
 2     public void fileDelete(){
 3 
 4         String filePath = "D:\\file1.txt";
 5 
 6         File file = new File(filePath);
 7 
 8         if(file.exists()){
 9             if(file.delete()){
10                 System.out.println(filePath+"删除成功");
11             }else {
12                 System.out.println(filePath+"删除失败");
13             };
14         }else{
15             System.out.println("文件不存在");
16         }
17     }

      运行结果:

 

 

 

    //删除目录

    

 1 @Test
 2     public void fileDeleteD(){
 3 
 4         String filePath = "D:\\file1.txt";
 5 
 6         File file = new File(filePath);
 7 
 8         if(file.exists()){
 9 
10             if(file.delete()){
11 
12                 System.out.println(filePath+"删除成功");
13             }else {
14                 System.out.println(filePath+"删除失败");
15             };
16 
17         }else{
18             System.out.println("目录不存在");
19         }
20     }

  运行结果:

 

 

 

    //判断目录是否存在,不存在就创建

    

 1 @Test
 2     public void fileDeleteD1(){
 3 
 4         String dirPath = "D:\\test\\dir1.txt";
 5 
 6         File file = new File(dirPath);
 7 
 8         if(file.exists()){
 9 
10             System.out.println(dirPath+"该目录已经存在");
11 
12         }else{
13 
14             if(file.mkdirs()){
15 
16                 System.out.println("创建成功");
17 
18             }else {
19 
20                 System.out.println("创建失败");
21 
22             };
23 
24         }
25 
26     }

  运行结果:

 

 

 

 

4、IO流原理及流的分类

  1、I=input,O=output,用于处理数据传输,读写文件、网络通信

  2、Java程序中,输入输出以流的形式进行

  3、java.io包下

 

  流的分类:

  按操作数据单位不同可以分为:字节流(8bit)、字符流(字符,对应字节按照编码确定)

  效率:字符流更好,字节流的存在是为了更好的处理二进制文件,音视频

  按流向不同可以分为:输入流、输出流

  按流的角色不同分为:节点流、处理流

 

 

 

 

 

 

public abstract class InputStream implements Closeable {

    private static final int MAX_SKIP_BUFFER_SIZE = 2048;

 

    public InputStream() {

    }

 

    public abstract int read() throws IOException;

 

    public int read(byte[] var1) throws IOException {

        return this.read(var1, 0, var1.length);

    }

 

 

 

public abstract class OutputStream implements Closeable, Flushable {

    public OutputStream() {

    }

}

 

 

 

public abstract class Writer implements Appendable, Closeable, Flushable{

   

}

 

 

 

public abstract class Reader implements Readable, Closeable {

   

}

前面四个都是抽象类,想要使用必须实现其具体方法

 

 

 

5、Scanner与Println

  1、基本键盘输入

 

import org.testng.annotations.Test;

 

import java.util.Scanner;

 

public class scanPrintTest {

    public static void main(String[] args) {

        //创建Scanner对象,接受从控制台输入

        Scanner input = new Scanner(System.in);

        //接受String类型

        String str = input.next();

        //输出结果

        System.out.println(str);

 

        System.out.println(“hello world”);

 

    }

 

 

}

2、常见键盘输入类型

import java.util.Scanner;

 

public class scanTest {

 

    public static void main(String[] args) {

        Scanner input =new Scanner(System.in);

        //double类型的数据

        System.out.print(“请输入一个double类型的数:”);

        double d = input.nextDouble();

        System.out.println(d);

        //int类型的数据

        System.out.print(“请输入一个int类型的数:”);

        int i = input.nextInt();

        System.out.println(i);

        //字符串类型的数据

        System.out.print(“请输入一个string类型的数:”);

        String s = input.next();

        System.out.println(s);

    }

 

}

6、InputStream

常见的子类

FileInputStream:文件输入流

BufferedStream:缓冲字节输入流

ObjectedStream:对象字节输入流

 

import org.testng.annotations.Test;

 

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

 

public class fileInputStream {

    public static void main(String[] args) {

 

    }

    

  //1.读取文件

 1 @Test
 2     public void fileIn1(){
 3         String filePath = "D:\\testfile.txt";
 4         int readData;
 5         FileInputStream fileInputStream = null;
 6         try{
 7             //创建FileInputStream对象,用于读取文件
 8             fileInputStream = new FileInputStream(filePath);
 9 
10             while ((readData = fileInputStream.read()) != -1){
11                 System.out.print((char)readData);
12             };
13 
14         }catch (IOException e){
15             e.printStackTrace();
16         }finally {
17             //关闭文件流
18             try {
19                 fileInputStream.close();
20             } catch (IOException e) {
21                 throw new RuntimeException(e);
22             }
23 
24         }
25 
26     }

  运行结果:

 

 

   //2.读取文件

 1 @Test
 2     public void fileIn2(){
 3         String filePath = "D:\\testfile.txt";
 4         int readData;
 5         int readlength = 0;
 6         //字节数组
 7         byte[] buf = new byte[8];
 8         FileInputStream fileInputStream = null;
 9         try{
10             //创建FileInputStream对象,用于读取文件
11             fileInputStream = new FileInputStream(filePath);
12             while ((readlength = fileInputStream.read(buf)) != -1){
13                 System.out.println(new String(buf,0,readlength));
14             };
15         }catch (IOException e){
16             e.printStackTrace();
17         }finally {
18 
19             //关闭文件流
20             try {
21                 fileInputStream.close();
22             } catch (IOException e) {
23                 throw new RuntimeException(e);
24             }
25 
26         }
27 
28     }

  运行结果:

 

 

 

    //3.读取文件

 

 1 @Test
 2     public void fileIn3(){
 3         String filePath = "D:\\testfile.txt";
 4         int readData;
 5         int readlength = 0;
 6         //字节数组
 7         byte[] buf = new byte[8];
 8 
 9         FileInputStream fileInputStream = null;
10         try{
11             //创建FileInputStream对象,用于读取文件
12             fileInputStream = new FileInputStream(filePath);
13 
14             while ((readlength = fileInputStream.read(buf)) != -1){
15                 System.out.println(new String(buf,0,readlength));
16             };
17 
18         }catch (IOException e){
19             e.printStackTrace();
20         }finally {
21 
22             //关闭文件流
23             try {
24                 fileInputStream.close();
25             } catch (IOException e) {
26                 throw new RuntimeException(e);
27             }
28 
29         }
30 
31     }

  运行结果:

 

 

 

 

7、OutputStream

1、FileOutputStream

例子:使用FileOutputStream在文件夹中写入“hello world”,如果文件不存在,会创建文件

 

import org.testng.annotations.Test;

 

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

 

public class outputStream {

 

    public static void main(String[] args) {

 

    }

    //使用FileOutputStream将数据写到文件中

    //如果文件不存在,则创建文件

    

 1 @Test
 2     public void writeFile(){
 3         String filePath = "d:\\fileout.txt";
 4 
 5         //创建对象
 6         FileOutputStream fileOutputStream = null;
 7 
 8         try {
 9             fileOutputStream = new FileOutputStream(filePath);
10             //1、写入一个字节
11             //fileOutputStream.write('H');
12             //2、写入一个字符串
13             //String str = "hello socket";
14             //str.getBytes()将字符串转换成字节数组
15             //fileOutputStream.write(str.getBytes());
16 
17             //3、写入字符串
18             String str = "hello lst";
19             fileOutputStream.write(str.getBytes(),0,str.length());
20 
21         } catch (IOException e) {
22             e.printStackTrace();
23         }finally {
24             try {
25                 fileOutputStream.close();
26             } catch (IOException e) {
27                 throw new RuntimeException(e);
28 
29             }
30 
31         }
32 
33     }

  运行结果:

 

 

 

 

 

 

 

8、文件复制

 1 package com.itcast.demo1;
 2 import java.io.File;
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 
 6 public class Test9 {
 7     //file读和写实现复制文件
 8     public static void main(String[] args) throws Exception {
 9         //创建file对象
10         File f=new File("d:\\test.txt");
11         //判断文件是否存在
12         if(f.exists()){
13             System.out.println("test.txt存在,可以复制");
14         }else{
15             f.createNewFile();
16             System.out.println("test.txt不存在,新建成功,可以复制");
17         }
18 
19         //创建FileInputStream对象
20         FileInputStream inp=new FileInputStream(f);
21         //判断demo目录是否存在
22         File f1=new File("d:\\demo");
23         if(f1.isDirectory()){
24             FileOutputStream out=new FileOutputStream("e:\\demo\\"+f.getName());
25             byte bytes[]=new byte[1024];
26             int temp=0;  //边读边写
27             while((temp=inp.read(bytes))!=-1){  //
28                 out.write(bytes,0,temp);   //
29             }
30             //结束
31             inp.close();
32             out.close();
33             System.out.println("文件拷贝成功!");
34         }else{
35             //新建demo目录
36             f1.mkdir();
37             System.out.println("demo目录不存在,已经新建成功,继续复制");
38             FileOutputStream out=new FileOutputStream("d:\\demo\\"+f.getName());
39             byte bytes[]=new byte[1024];
40             int temp=0;  //边读边写
41             while((temp=inp.read(bytes))!=-1){  //
42                 out.write(bytes,0,temp);   //
43             }
44             //结束
45             inp.close();
46             out.close();
47             System.out.println("文件拷贝成功!");
48         }
49 
50     }
51 
52 }

  运行结果:

 

 

 

原文地址:http://www.cnblogs.com/royol/p/16859193.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性