首页 > 其他分享 >文件的相关操作

文件的相关操作

时间:2022-11-05 23:36:10浏览次数:39  
标签:文件 String System File new println 相关 操作 out

一、文件的概念

  文件是具有符号名的、在逻辑上具备完整意义的一组具备相关性的信息项的有序序列,可用于存储数据。其中信息项是构成文件内容的基本单位。除此之外。文件一般存储在外存介质上。

二、文件流

  在Java中,文件的输入与输出一般均通过流(Stream)的形式来实现。针对于流而言,其并不关系数据如何进行传输,仅通过向源端输入数据,从目的端获取数据即可。除此之外,流可以根据处理数据的单位划分为字节流(仅读取字节数组)和字符流(仅读取字符数组)两种,而根据其实现功能则可以划分为输入流(读取文件)和输出流(写入文件)。

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

  字节流:处理单元为1字节(byte)。

  字符流:处理单元为2字节的Unicode字符。

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

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

抽象基类 字节流 字符流
输入流 InputStream Reader
输出流 OutputStream Writer

  备注:在同一传输过程中,输入流与输出流的处理数据的单位具备一致性,即字节输入流,字节输出流;字符输入流,字符输出流。除此之外,1Unicode = 2Byte = 16bit。

三、文件的相关操作

  1、创建文件对象的相关构造器及其相应方法

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

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

  根据父目录进行子路径构建:new File(String parent,Stringchild)

复制代码
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;

public class testCreate {
    public static void main(String[] args){

    }
    //方式一
    @Test
    public void create1(){
        String filePath = "D:\\tcp.txt";
        File file = new File(filePath);
        try{
            file.createNewFile();
            System.out.println("创建成功");
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    //方式二
    @Test
    public void create2(){
        File parentFile = new File("D:\\");
        String fileName = "file_2.docx";
        File file = new File(parentFile,fileName);
        try{
            file.createNewFile();
            System.out.println("创建成功");
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    //方式三
    @Test
    public void create3(){
        String parentPath = "D:\\";
        String filePath = "file_3.docx";
        File file = new File(parentPath,filePath);
        try{
            file.createNewFile();
            System.out.println("创建成功");
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
复制代码

  备注:三种创建文件的方法最好选择单独运行以便于能够成功创建相关文件。

  2、文件相关信息获取

   UTF-8编码方式:1个英文字母占1个字节(1Byte = 8bit),1个汉字占3个字节(3Byte = 3×8bit),1个英文状态下的标点符号占1个字节,1个中文状态下的标点符号占3个字节,一个换行符占2个字节。

 

复制代码
import org.testng.annotations.Test;

import java.io.File;

public class Information {
    public static void main(String[] args){

    }
    //获取文件信息
    @Test
    public void Info(){
        //创建文件对象
        File file = new File("D:\\friendship.txt");
        //调用方法得出相应信息
        System.out.println("文件父目录:" + file.getParent());
        System.out.println("文件大小(字节):" + file.length());
        System.out.println("文件是否存在:" + file.exists());
        System.out.println("是否为文件:" + file.isFile());
        System.out.println("是否为目录:" + file.isDirectory());
    }
}
复制代码

 

  3、文件的目录操作

  mkdir:创建一级目录。

  mkdirs:创建多级目录。

  delete:删除空白目录或文件。

复制代码
import org.testng.annotations.Test;

import java.io.File;

public class directory {
    public static void main(String[] args){

    }
    //删除文件
    @Test
    public void fileDelete(){
        String filePath = "D:\\file_1.docx";
        File file = new File(filePath);
        if(file.exists()){
            if(file.delete()){
                System.out.println(filePath + "删除成功");
            }
            else{
                System.out.println(filePath + "删除失败");
            }
        }
        else{
            System.out.println("文件不存在");
        }
    }
    //删除目录
    @Test
    public void fileDeleted(){
        String filePath = "D:\\file_1.docx";
        File file = new File(filePath);
        if(file.exists()){
            if(file.delete()){
                System.out.println(filePath + "删除成功");
            }
            else{
                System.out.println(filePath + "删除失败");
            }
        }
        else{
            System.out.println("文件不存在");
        }
    }
    //判断目录是否存在,不存在时创建目录
    @Test
    public void fileDeleteds(){
        String dirPath = "D:\\test\\dir.txt";
        File file = new File(dirPath);
        if(file.exists()){
            System.out.println(dirPath + "该目录已存在");
        }
        else{
            if(file.mkdirs()){
                System.out.println("创建成功");
            }
            else{
                System.out.println("创建失败");
            }
        }
    }
}
复制代码

  4、Scanner与Println

   ①基本键盘输入

复制代码
import java.util.Scanner;

public class scannertest {
    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");
    }
}
复制代码

  ②常见键盘输入类型

复制代码
import java.util.Scanner;

public class printlntest {
    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);
    }
}
复制代码

  5、InputStream

  文件输入流:FileInputStream

  缓冲字节输入流:BufferedStream

  对象字节输入流:ObjectedStream

复制代码
import org.testng.annotations.Test;

import java.io.FileInputStream;
import java.io.IOException;

public class InputStream {
    public static void main(String[] args){

    }

    @Test
    public void fileIn1(){
        String filePath = "D:\\testfile.txt";
        int readData;
        FileInputStream fileInputStream = null;
        try{
            //创建FileInputStream对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);

            while ((readData = fileInputStream.read()) != -1){
                System.out.println((char)readData);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            //关闭文件流
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Test
    public void fileIn2(){
        String filePath = "D:\\testfile.txt";
        int readData;
        int readlength = 0;
        //字节数组
        byte[] buf = new byte[8];
        FileInputStream fileInputStream = null;
        try{
            //创建FileInputStream对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            while ((readlength = fileInputStream.read(buf)) != -1){
                System.out.println(new String(buf,0,readlength));
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            //关闭文件流
            try {
                fileInputStream.close();
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Test
    public void fileIn3(){
        String filePath = "D:\\testfile.txt";
        int readData;
        int readlength = 0;
        //字节数组
        byte[] buf = new byte[8];
        FileInputStream fileInputStream = null;
        try{
            //创建FileInputStream对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            while ((readlength = fileInputStream.read(buf)) != -1){
                System.out.println(new String(buf,0,readlength));
            }
        }
        catch (IOException e){
            e.printStackTrace();
        }
        finally {
            //关闭文件流
            try {
                fileInputStream.close();
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
复制代码

  6、OutputStream

  使用“FIleOutputStream”在文件夹中写入“××”,若文件不存在,则会直接创建相关文件。

复制代码
import org.testng.annotations.Test;

import java.io.FileOutputStream;
import java.io.IOException;

public class outputStream {
    public static void main(String[] args) {
    }
    //使用FileOutputStream将数据写到文件中
    //如果文件不存在,则创建文件
    @Test
    public void writeFile(){
        String filePath = "d:\\fileout.txt";
        //创建对象
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(filePath);
            //1、写入一个字节
            //fileOutputStream.write('H');
            //2、写入一个字符串
            //String str = "hello socket";
            //str.getBytes()将字符串转换成字节数组
            //fileOutputStream.write(str.getBytes());
            //3、写入字符串
            String str = "hello lst";
            fileOutputStream.write(str.getBytes(),0,str.length());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                fileOutputStream.close();
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
复制代码

  7、 文件复制

  判断文件是否存在,存在则进行复制操作,反之则直接创建文件。

复制代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class copyPic {
    //file读和写实现复制文件
    public static void main(String[] args) throws Exception {
        //创建file对象
        File f=new File("d:\\test.jpg");
        //判断文件是否存在
        if(f.exists()){
            System.out.println("test.jpg存在,可以复制");
        }
        else{
            f.createNewFile();
            System.out.println("test.jpg不存在,新建成功,可以复制");
        }
        //创建FileInputStream对象
        FileInputStream inp=new FileInputStream(f);
        //创建FileOutputStream对象
        //判断demo目录是否存在
        File f1=new File("d:\\demo");
        if(f1.isDirectory()){
            FileOutputStream out=new FileOutputStream("e:\\demo\\"+f.getName());
            byte bytes[]=new byte[1024];
            int temp=0;  //边读边写
            while((temp=inp.read(bytes))!=-1){  //读
                out.write(bytes,0,temp);   //写
            }
            //结束
            inp.close();
            out.close();
            System.out.println("文件拷贝成功!");
        }
        else{
            //新建demo目录
            f1.mkdir();
            System.out.println("demo目录不存在,已经新建成功,继续复制");
            FileOutputStream out=new FileOutputStream("d:\\demo\\"+f.getName());
            byte bytes[]=new byte[1024];
            int temp=0;  //边读边写
            while((temp=inp.read(bytes))!=-1){  //读
                out.write(bytes,0,temp);   //写
            }
            //结束
            inp.close();
            out.close();
            System.out.println("文件拷贝成功!");
        }
    }
}
 

标签:文件,String,System,File,new,println,相关,操作,out
From: https://www.cnblogs.com/taojj/p/16861679.html

相关文章

  • 盘点一个Pandas新手在文件读取路上遇到的问题
    大家好,我是皮皮。一、前言国庆期间在Python铂金交流群【暮雨和】问了一个Pandas处理的问题,提问截图如下:代码截图如下:新手上路,遇到的问题还是挺多的。二、实现过程......
  • shell-文件查找命令笔记三
    文件查找-find命令格式:find[路径][选项][操作]选项-name根据文件名查找-iname根据文件名查找,忽略大小写-perm根据文件权限查找find/etc-perm777-prun......
  • Openssl Des3对压缩文件进行加密命令详解
    群友提问:致力于明天:tar-cvf-WMG_Back_"$Today"|openssldes3-salt-khY91gd3GJAAfghECleLwWQAPGK9Cxs-out$dir_backup_today.tar.des3致力于明天:有人懂这个......
  • 34、Java——一个案例学会Dom4j解析技术对XML文件的增删改查
    ✅作者简介:热爱国学的Java后端开发者,修心和技术同步精进。案例使用Dom4j解析技术实现对animal.xml文件进行增删改查操作。链接:​​dom4j包下载​​​将dom4j的jar包导入......
  • 001.项目初始化,生成逆向文件
    1.整合Mybatis1.1在pom.xml中添加文件<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-......
  • git的基本操作
    git的基本操作可以去看git的菜鸟教程:https://www.runoob.com/git/git-basic-operations.html初始化仓库建好后需要先进入要上传的文件夹进入命令行模式进入后先gi......
  • java 文件类
    java常用的文件操作1~文件的创建(三种不同方法):(1)根据路径构建一个File对象:newFile(Stringpathname)(2)根据父目录文件+子路径构建:newFile(Fileparent,Stringchild)(3)......
  • Qt获取文件存储路径,绝对路径与相对路径,斜杠与反斜杠转换
     Qt获取文件存储路径QStringdirPath=QFileDialog::getExistingDirectory(this,tr("浏览选择文件夹"),tr("C:"));//返回用户选择的路径if(dirPath.isEmpty())//......
  • 操作系统速成——3.内存管理
    三.内存管理引入目的:更好的支持多道程序的并发执行,提高系统性能主要功能:内存空间的分配与回收、存储的保护和共享、地址转换、内存扩充 存储的保护和共享就是说各道作......
  • 更新:删除指定文件夹下所有重复文件
    #!/usr/bin/python3.9#2022-11-05还可优化代码有冗余importosimporthashlibimporttimeimportsysdefchoiceWhat(): """ #选择功能 #1手动输入路径......