欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 文件操作一(写文件、按行读文件、删除文件、复制文件、追加数据、创建临时文件、修改最后修改日期、获取文件大小)

程序员文章站 2022-04-15 19:12:34
文件写入import java.io.*; public class Main { public static void main(String[] args) { try { BufferedWriter out = new BufferedWriter(new FileWriter("sanguo.txt")); out.write("三国教程"); out.close();...

文件写入

import java.io.*;
 
public class Main {
    public static void main(String[] args)  {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter("sanguo.txt"));
            out.write("三国教程");
            out.close();
            System.out.println("文件创建成功!");
        } catch (IOException e) {
        }
    }
}

以上代码运行输出结果为:

文件创建成功!

 

读取文件内容

import java.io.*;
 
public class Main {
    public static void main(String[] args)  {
        try {
            BufferedReader in = new BufferedReader(new FileReader("test.log"));
            String str;
            while ((str = in.readLine()) != null) {
                System.out.println(str);
            }
            System.out.println(str);
        } catch (IOException e) {
        }
    }
}

以上代码运行输出结果为:

111
222
333

 

删除文件

import java.io.*;
 
public class Main
{
    public static void main(String[] args)
    {
        try{
            File file = new File("c:\\test.txt");
            if(file.delete()){
                System.out.println(file.getName() + " 文件已被删除!");
            }else{
                System.out.println("文件删除失败!");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

以上代码运行输出结果为(需要在 C 盘上先创建 test.txt 文件):

test.txt 文件已被删除!

 

将文件内容复制到另一个文件

import java.io.*;
 
public class Main {
    public static void main(String[] args) throws Exception {
        BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
        out1.write("string to be copied\n");
        out1.close();
        InputStream in = new FileInputStream(new File("srcfile"));
        OutputStream out = new FileOutputStream
        (new File("destnfile"));
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        BufferedReader in1 = new BufferedReader(new FileReader("destnfile"));
        String str;
        while ((str = in1.readLine()) != null) {
            System.out.println(str);
        }
        in1.close();
    }
}

以上代码运行输出结果为:

string to be copied

 

向文件中追加数据

import java.io.*;
 
public class Main {
    public static void main(String[] args) throws Exception {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter("filename"));
            out.write("aString1\n");
            out.close();
            out = new BufferedWriter(new FileWriter("filename",true));
            out.write("aString2");
            out.close();
            BufferedReader in = new BufferedReader(new FileReader("filename"));
            String str;
            while ((str = in.readLine()) != null) {
                System.out.println(str);
            }
            in.close();
        }
            catch (IOException e) {
            System.out.println("exception occoured"+ e);
        }
    }
}

以上代码运行输出结果为:

aString1
aString2

 

创建临时文件

//默认临时路径

import java.io.*;
 
public class Main {
    public static void main(String[] args) throws Exception {
        File temp = File.createTempFile("testrunoobtmp", ".txt");
        System.out.println("文件路径: "+temp.getAbsolutePath());
        temp.deleteOnExit();
        BufferedWriter out = new BufferedWriter(new FileWriter(temp));
        out.write("aString");
        System.out.println("临时文件已创建:");
        out.close();
    }
}
// 指定临时路径

import java.io.File;
 
public class Main {
 
   public static void main(String[] args) {      
      File f = null;
            
      try {
      
         // 创建临时文件
         f = File.createTempFile("tmp", ".txt", new File("C:/"));
         
         // 输出绝对路径
         System.out.println("File path: "+f.getAbsolutePath());
         
         // 终止后删除临时文件
         f.deleteOnExit();
         
         // 创建临时文件
         f = File.createTempFile("tmp", null, new File("D:/"));
         
         // 输出绝对路径
         System.out.print("File path: "+f.getAbsolutePath());
         
         // 终止后删除临时文件
         f.deleteOnExit();
         
      } catch(Exception e) {
      
         // 如果有错误输出内容
         e.printStackTrace();
      }
   }
}

 

修改文件最后的修改日期

import java.io.File;
import java.util.Date;
 
public class Main {
    public static void main(String[] args) throws Exception {
        File fileToChange = new File("C:/myjavafile.txt");
        fileToChange.createNewFile();
        Date filetime = new Date(fileToChange.lastModified());
        System.out.println(filetime.toString());
        System.out.println(fileToChange.setLastModified(System.currentTimeMillis()));
        filetime = new Date(fileToChange.lastModified());
        System.out.println(filetime.toString());
    }
}

以上代码运行输出结果为:

Sat Mar 21 22:00:48 CST 2015
true
Fri Apr 10 11:09:19 CST 2015

 

获取文件大小

import java.io.File;
 
public class Main {
    public static long getFileSize(String filename) {
        File file = new File(filename);
        if (!file.exists() || !file.isFile()) {
            System.out.println("文件不存在");
            return -1;
        }
        return file.length();
    }
    public static void main(String[] args) {
        long size = getFileSize("c:/java.txt");
        System.out.println("java.txt文件大小为: " + size);
    }
}

以上代码运行输出结果为(java.txt 文件位于 C 盘):

java.txt文件大小为: 480

 

本文地址:https://blog.csdn.net/u012206617/article/details/107684484

相关标签: Java