Java中的File操作总结

 

1.创建文件

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

public class CreateFileExample
{
    public static void main( String[] args ) { try { File file = new File("c:\\newfile.txt"); //创建文件使用createNewFile()方法 if (file.createNewFile()){ System.out.println("File is created!"); }else{ System.out.println("File already exists."); } } catch (IOException e) { e.printStackTrace(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

2.建立文件路径

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

public class FilePathExample1 {
    public static void main(String[] args) { try { String filename = "newFile.txt"; String workingDirectory = System.getProperty("user.dir"); //****************// String absoluteFilePath = ""; //absoluteFilePath = workingDirectory + System.getProperty("file.separator") + filename; absoluteFilePath = workingDirectory + File.separator + filename; System.out.println("Final filepath : " + absoluteFilePath); //****************// File file = new File(absoluteFilePath); if (file.createNewFile()) { System.out.println("File is created!"); } else { System.out.println("File is already existed!"); } } catch (IOException e) { e.printStackTrace(); } } } ///////////////////////////////////////////////////////////////// import java.io.File; import java.io.IOException; public class FilePathExample2 { public static void main(String[] args) { try { String filename = "newFile.txt"; String workingDirectory = System.getProperty("user.dir"); //****************// File file = new File(workingDirectory, filename); //****************// System.out.println("Final filepath : " + file.getAbsolutePath()); if (file.createNewFile()) { System.out.println("File is created!"); } else { System.out.println("File is already existed!"); } } catch (IOException e) { e.printStackTrace(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

3.设置文件权限

@检查文件权限是否设置

  • file.canExecute()
  • file.canWrite()
  • file.canRead()

@设置权限 
- file.setExecutable(boolean) 
- file.setReadable(boolean) 
- file.setWritable(boolean)

代码演示 :

package com.File;
import java.io.File; import java.io.IOException; public class FilePermissionExample { public static void main( String[] args ) { try { //1.未设置权限 File file = new File("D:\\2.txt"); // if(file.exists()){ // System.out.println("是否可执行: " + file.canExecute()); // System.out.println("是否可写 : " + file.canWrite()); // System.out.println("是否可读 : " + file.canRead()); // } //2.已设置权限 file.setExecutable(false); file.setReadable(false); file.setWritable(false); System.out.println(" 是否可执行: " + file.canExecute()); System.out.println("是否可写 : " + file.canWrite()); System.out.println("是否可读 : " + file.canRead()); if (file.createNewFile()){ System.out.println("文件已创建!"); }else{ System.out.println("文件已存在"); } } catch (IOException e) { e.printStackTrace(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

4.读取文本内容的重要几个流

  • BufferedInputStream
  • FileInputStream
  • FileReader
  • BufferedReader
  • FileInputStream
  • DataInputStream

@.BufferedInputStream、 DataInputStream的使用

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class BufferedInputStreamExample { public static void main(String[] args) { File file = new File("C:\\testing.txt"); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); while (dis.available() != 0) { System.out.println(dis.readLine()); } } catch (IOException e) { e.printStackTrace(); } finally { try { fis.close(); bis.close(); dis.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

@ FileInputStream的使用

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFileExample {

    public static void main(String[] args) { File file = new File("C:/robots.txt"); FileInputStream fis = null; try { fis = new FileInputStream(file); System.out.println("Total file size to read (in bytes) : " + fis.available()); int content; while ((content = fis.read()) != -1) { // convert to char and display it System.out.print((char) content); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) fis.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

@BufferedReader的使用

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample1 { private static final String FILENAME = "E:\\test\\filename.txt"; public static void main(String[] args) { BufferedReader br = null; FileReader fr = null; try { //br = new BufferedReader(new FileReader(FILENAME)); fr = new FileReader(FILENAME); br = new BufferedReader(fr); String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); if (fr != null) fr.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } ################################################################# import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileExample2 { private static final String FILENAME = "E:\\test\\filename.txt"; public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader(FILENAME))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } } } #################################################################
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77

5.写入文本的几个重要的流

扫描二维码关注公众号,回复: 5344784 查看本文章
  • BufferedOutputStream
  • FileOutputStream
  • FileWriter
  • BufferedWriter
  • FileOutputStream
  • DataOutputStream

@FileOutputStream 的使用

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

public class WriteFileExample { public static void main(String[] args) { File file = new File("c:/newfile.txt"); String content = "This is the text content"; try (FileOutputStream fop = new FileOutputStream(file)) { // if file doesn't exists, then create it if (!file.exists()) { file.createNewFile(); } // get the content in bytes byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

@BufferedWriter的使用


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample2 { private static final String FILENAME = "E:\\test\\filename.txt"; public static void main(String[] args) { try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME))) { String content = "This is the content to write into file\n"; bw.write(content); // no need to close it. //bw.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

6.向文件中添加新的内容

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendToFileExample { private static final String FILENAME = "E:\\test\\filename.txt"; public static void main(String[] args) { BufferedWriter bw = null; FileWriter fw = null; try { String data = " This is new content"; File file = new File(FILENAME); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } // true = append file fw = new FileWriter(file.getAbsoluteFile(), true); bw = new BufferedWriter(fw); bw.write(data); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } finally { try { if (bw != null) bw.close(); if (fw != null) fw.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

7.删除文件

mport java.io.File;

public class DeleteFileExample
{
    public static void main(String[] args) { try{ File file = new File("c:\\logfile20100131.log"); if(file.delete()){ System.out.println(file.getName() + " is deleted!"); }else{ System.out.println("Delete operation is failed."); } }catch(Exception e){ e.printStackTrace(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

8.删除指定格式的所有文件

import java.io.*;

public class FileChecker { private static final String FILE_DIR = "c:\\folder"; private static final String FILE_TEXT_EXT = ".txt"; public static void main(String args[]) { new FileChecker().deleteFile(FILE_DIR,FILE_TEXT_EXT); } public void deleteFile(String folder, String ext){ GenericExtFilter filter = new GenericExtFilter(ext); File dir = new File(folder); //list out all the file name with .txt extension String[] list = dir.list(filter); if (list.length == 0) return; File fileDelete; for (String file : list){ String temp = new StringBuffer(FILE_DIR) .append(File.separator) .append(file).toString(); fileDelete = new File(temp); boolean isdeleted = fileDelete.delete(); System.out.println("file : " + temp + " is deleted : " + isdeleted); } } //inner class, generic extension filter public class GenericExtFilter implements FilenameFilter { private String ext; public GenericExtFilter(String ext) { this.ext = ext; } public boolean accept(File dir, String name) { return (name.endsWith(ext)); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

9.查找以某种格式的所有文件

import java.io.*;

public class FindCertainExtension { private static final String FILE_DIR = "c:\\folder"; private static final String FILE_TEXT_EXT = ".jpg"; public static void main(String args[]) { new FindCertainExtension().listFile(FILE_DIR, FILE_TEXT_EXT); } public void listFile(String folder, String ext) { GenericExtFilter filter = new GenericExtFilter(ext); File dir = new File(folder); if(dir.isDirectory()==false){ System.out.println("Directory does not exists : " + FILE_DIR); return; } // list out all the file name and filter by the extension String[] list = dir.list(filter); if (list.length == 0) { System.out.println("no files end with : " + ext); return; } for (String file : list) { String temp = new StringBuffer(FILE_DIR).append(File.separator) .append(file).toString(); System.out.println("file : " + temp); } } // inner class, generic extension filter public class GenericExtFilter implements FilenameFilter { private String ext; public GenericExtFilter(String ext) { this.ext = ext; } public boolean accept(File dir, String name) { return (name.endsWith(ext)); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

10.修改文件名

import java.io.File;

public class RenameFileExample
{
    public static void main(String[] args) { File oldfile =new File("oldfile.txt"); File newfile =new File("newfile.txt"); if(oldfile.renameTo(newfile)){ System.out.println("Rename succesful"); }else{ System.out.println("Rename failed"); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

11.复制文件内容

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; import java.io.OutputStream; public class CopyFileExample { public static void main(String[] args) { InputStream inStream = null; OutputStream outStream = null; try{ File afile =new File("Afile.txt"); File bfile =new File("Bfile.txt"); inStream = new FileInputStream(afile); outStream = new FileOutputStream(bfile); byte[] buffer = new byte[1024]; int length; //copy the file content in bytes while ((length = inStream.read(buffer)) > 0){ outStream.write(buffer, 0, length); } inStream.close(); outStream.close(); System.out.println("File is copied successful!"); }catch(IOException e){ e.printStackTrace(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

12.将一个文件移到另一个目录

import java.io.File;

public class MoveFileExample
{
    public static void main(String[] args) { try{ File afile =new File("C:\\folderA\\Afile.txt"); if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){ System.out.println("File is moved successful!"); }else{ System.out.println("File is failed to move!"); } }catch(Exception e){ e.printStackTrace(); } } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

13.创建文件是添加日期

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class GetFileCreationDateExample
{
    public static void main(String[] args) { try{ Process proc = Runtime.getRuntime().exec("cmd /c dir c:\\logfile.log /tc"); BufferedReader br = new BufferedReader( new InputStreamReader(proc.getInputStream())); String data =""; //it's quite stupid but work for(int i=0; i<6; i++){ data = br.readLine(); } System.out.println("Extracted value : " + data); //split by space StringTokenizer st = new StringTokenizer(data); String date = st.nextToken();//Get date String time = st.nextToken();//Get time System.out.println("Creation Date : " + date); System.out.println("Creation Time : " + time); }catch(IOException e){ e.printStackTrace(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

14.获取文件被修改的日期

import java.io.File;
import java.text.SimpleDateFormat;

public class GetFileLastModifiedExample
{
    public static void main(String[] args) { File file = new File("c:\\logfile.log"); System.out.println("Before Format : " + file.lastModified()); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); System.out.println("After Format : " + sdf.format(file.lastModified())); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

15.修改文件日期

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat; import java.util.Date; public class ChangeFileLastModifiedExample { public static void main(String[] args) { try{ File file = new File("C:\\logfile.log"); //print the original last modified date SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); System.out.println("Original Last Modified Date : " + sdf.format(file.lastModified())); //set this date String newLastModified = "01/31/1998"; //need convert the above date to milliseconds in long value Date newDate = sdf.parse(newLastModified); file.setLastModified(newDate.getTime()); //print the latest last modified date System.out.println("Lastest Last Modified Date : " + sdf.format(file.lastModified())); }catch(ParseException e){ e.printStackTrace(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

16.设置文件只能读

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

public class FileReadAttribute
{

    public static void main(String[] args) throws IOException { File file = new File("c:/file.txt"); //mark this file as read only, since jdk 1.2 file.setReadOnly(); if(file.canWrite()){ System.out.println("This file is writable"); }else{ System.out.println("This file is read only"); } //revert the operation, mark this file as writable, since jdk 1.6 file.setWritable(true); if(file.canWrite()){ System.out.println("This file is writable"); }else{ System.out.println("This file is read only"); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

17.获取文件大小

import java.io.File;

public class FileSizeExample
{
    public static void main(String[] args) { File file =new File("c:\\java_xml_logo.jpg"); if(file.exists()){ double bytes = file.length(); double kilobytes = (bytes / 1024); double megabytes = (kilobytes / 1024); double gigabytes = (megabytes / 1024); double terabytes = (gigabytes / 1024); double petabytes = (terabytes / 1024); double exabytes = (petabytes / 1024); double zettabytes = (exabytes / 1024); double yottabytes = (zettabytes / 1024); System.out.println("bytes : " + bytes); System.out.println("kilobytes : " + kilobytes); System.out.println("megabytes : " + megabytes); System.out.println("gigabytes : " + gigabytes); System.out.println("terabytes : " + terabytes); System.out.println("petabytes : " + petabytes); System.out.println("exabytes : " + exabytes); System.out.println("zettabytes : " + zettabytes); System.out.println("yottabytes : " + yottabytes); }else{ System.out.println("File does not exists!"); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

18.获取文件路径

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

public class AbsoluteFilePathExample
{
    public static void main(String[] args) { try{ File temp = File.createTempFile("i-am-a-temp-file", ".tmp" ); String absolutePath = temp.getAbsolutePath(); System.out.println("File path : " + absolutePath); String filePath = absolutePath. substring(0,absolutePath.lastIndexOf(File.separator)); System.out.println("File path : " + filePath); }catch(IOException e){ e.printStackTrace(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

19.获取文件的总行数

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

public class LineNumberReaderExample { public static void main(String[] args) { try{ File file =new File("c:\\ihave10lines.txt"); if(file.exists()){ FileReader fr = new FileReader(file); LineNumberReader lnr = new LineNumberReader(fr); int linenumber = 0; while (lnr.readLine() != null){ linenumber++; } System.out.println("Total number of lines : " + linenumber); lnr.close(); }else{ System.out.println("File does not exists!"); } }catch(IOException e){ e.printStackTrace(); } } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

20.检查文件是否存在


import java.io.*;

public class FileChecker {

  public static void main(String args[]) { File f = new File("c:\\mkyong.txt"); if(f.exists()){ System.out.println("File existed"); }else{ System.out.println("File not found!"); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

21.检查 文件是否隐藏

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

public class FileHidden
{

    public static void main(String[] args) throws IOException { File file = new File("c:/hidden-file.txt"); if(file.isHidden()){ System.out.println("This file is hidden"); }else{ System.out.println("This file is not hidden"); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

22.读取文件为UTF-8的数据

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class test { public static void main(String[] args){ try { File fileDir = new File("c:\\temp\\test.txt"); BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream(fileDir), "UTF8")); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

23.向文件中写入UTF-8的数据

import java.io.BufferedWriter;
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; public class test { public static void main(String[] args){ try { File fileDir = new File("c:\\temp\\test.txt"); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(fileDir), "UTF8")); out.append("Website UTF-8").append("\r\n"); out.append("?? UTF-8").append("\r\n"); out.append("??????? UTF-8").append("\r\n"); out.flush(); out.close(); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

24.将 文本内容复制给一个变量

import java.io.DataInputStream;
import java.io.FileInputStream;

public class App{

    public static void main (String args[]) { try{ DataInputStream dis = new DataInputStream ( new FileInputStream ("c:\\logging.log")); byte[] datainBytes = new byte[dis.available()]; dis.readFully(datainBytes); dis.close(); String content = new String(datainBytes, 0, datainBytes.length); System.out.println(content); }catch(Exception ex){ ex.printStackTrace(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

25.生成文件校验值

import java.io.FileInputStream;
import java.security.MessageDigest;

public class TestCheckSum { public static void main(String args[]) throws Exception { String datafile = "c:\\INSTLOG.TXT"; MessageDigest md = MessageDigest.getInstance("SHA1"); FileInputStream fis = new FileInputStream(datafile); byte[] dataBytes = new byte[1024]; int nread = 0; while ((nread = fis.read(dataBytes)) != -1) { md.update(dataBytes, 0, nread); }; byte[] mdbytes = md.digest(); //convert the byte to hex format StringBuffer sb = new StringBuffer(""); for (int i = 0; i < mdbytes.length; i++) { sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); } System.out.println("Digest(in hex format):: " + sb.toString()); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

26.将文件转换成字节数组

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Paths; public class FileToArrayOfBytes { public static void main(String[] args) { try { // convert file to byte[] byte[] bFile = readBytesFromFile("C:\\temp\\testing1.txt"); //java nio //byte[] bFile = Files.readAllBytes(new File("C:\\temp\\testing1.txt").toPath()); //byte[] bFile = Files.readAllBytes(Paths.get("C:\\temp\\testing1.txt")); // save byte[] into a file Path path = Paths.get("C:\temp\\test2.txt"); Files.write(path, bFile); System.out.println("Done"); //Print bytes[] for (int i = 0; i < bFile.length; i++) { System.out.print((char) bFile[i]); } } catch (IOException e) { e.printStackTrace(); } } private static byte[] readBytesFromFile(String filePath) { FileInputStream fileInputStream = null; byte[] bytesArray = null; try { File file = new File(filePath); bytesArray = new byte[(int) file.length()]; //read file into bytes[] fileInputStream = new FileInputStream(file); fileInputStream.read(bytesArray); } catch (IOException e) { e.printStackTrace(); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return bytesArray; } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

27.文件保存字节数组

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class ArrayOfBytesToFile { private static final String UPLOAD_FOLDER = "C:\\temp\\"; public static void main(String[] args) { FileInputStream fileInputStream = null; try { File file = new File("C:\\temp\\testing1.txt"); byte[] bFile = new byte[(int) file.length()]; //read file into bytes[] fileInputStream = new FileInputStream(file); fileInputStream.read(bFile); //save bytes[] into a file writeBytesToFile(bFile, UPLOAD_FOLDER + "test1.txt"); writeBytesToFileClassic(bFile, UPLOAD_FOLDER + "test2.txt"); writeBytesToFileNio(bFile, UPLOAD_FOLDER + "test3.txt"); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } //Classic, < JDK7 private static void writeBytesToFileClassic(byte[] bFile, String fileDest) { FileOutputStream fileOuputStream = null; try { fileOuputStream = new FileOutputStream(fileDest); fileOuputStream.write(bFile); } catch (IOException e) { e.printStackTrace(); } finally { if (fileOuputStream != null) { try { fileOuputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } //Since JDK 7 - try resources private static void writeBytesToFile(byte[] bFile, String fileDest) { try (FileOutputStream fileOuputStream = new FileOutputStream(fileDest)) { fileOuputStream.write(bFile); } catch (IOException e) { e.printStackTrace(); } } //Since JDK 7, NIO private static void writeBytesToFileNio(byte[] bFile, String fileDest) { try { Path path = Paths.get(fileDest); Files.write(path, bFile); } catch (IOException e) { e.printStackTrace(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93

28.将字符串转换成InputStream

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class StringToInputStreamExample { public static void main(String[] args) throws IOException { String str = "This is a String ~ GoGoGo"; // convert String into InputStream InputStream is = new ByteArrayInputStream(str.getBytes()); // read it with BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

29.将InputStream转换为字符串

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class InputStreamToStringExample { public static void main(String[] args) throws IOException { // intilize an InputStream InputStream is = new ByteArrayInputStream("file content..blah blah".getBytes()); String result = getStringFromInputStream(is); System.out.println(result); System.out.println("Done"); } // convert InputStream to String private static String getStringFromInputStream(InputStream is) { BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

30.将文件转换为十六进制


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;

public class File2Hex
{
    public static void convertToHex(PrintStream out, File file) throws IOException { InputStream is = new FileInputStream(file); int bytesCounter =0; int value = 0; StringBuilder sbHex = new StringBuilder(); StringBuilder sbText = new StringBuilder(); StringBuilder sbResult = new StringBuilder(); while ((value = is.read()) != -1) { //convert to hex value with "X" formatter sbHex.append(String.format("%02X ", value)); //If the chracater is not convertable, just print a dot symbol "." if (!Character.isISOControl(value)) { sbText.append((char)value); }else { sbText.append("."); } //if 16 bytes are read, reset the counter, //clear the StringBuilder for formatting purpose only. if(bytesCounter==15){ sbResult.append(sbHex).append(" ").append(sbText).append("\n"); sbHex.setLength(0); sbText.setLength(0); bytesCounter=0; }else{ bytesCounter++; } } //if still got content if(bytesCounter!=0){ //add spaces more formatting purpose only for(; bytesCounter<16; bytesCounter++){ //1 character 3 spaces sbHex.append(" "); } sbResult.append(sbHex).append(" ").append(sbText).append("\n"); } out.print(sbResult); is.close(); } public static void main(String[] args) throws IOException { //display output to console convertToHex(System.out, new File("c:/file.txt")); //write the output into a file convertToHex(new PrintStream("c:/file.hex"), new File("c:/file.txt")); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

31.File如何得到空闲磁盘空间


import java.io.File;

public class DiskSpaceDetail
{
    public static void main(String[] args) { File file = new File("c:"); long totalSpace = file.getTotalSpace(); //total disk space in bytes. long usableSpace = file.getUsableSpace(); ///unallocated / free disk space in bytes. long freeSpace = file.getFreeSpace(); //unallocated / free disk space in bytes. System.out.println(" === Partition Detail ==="); System.out.println(" === bytes ==="); System.out.println("Total size : " + totalSpace + " bytes"); System.out.println("Space free : " + usableSpace + " bytes"); System.out.println("Space free : " + freeSpace + " bytes"); System.out.println(" === mega bytes ==="); System.out.println("Total size : " + totalSpace /1024 /1024 + " mb"); System.out.println("Space free : " + usableSpace /1024 /1024 + " mb"); System.out.println("Space free : " + freeSpace /1024 /1024 + " mb"); } }

猜你喜欢

转载自www.cnblogs.com/mashuqi/p/10445876.html