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.写入文本的几个重要的流
- 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");
}
}
Java中的File操作总结的更多相关文章
- java学习(九) —— java中的File文件操作及IO流概述
前言 流是干什么的:为了永久性的保存数据. IO流用来处理设备之间的数据传输(上传和下载文件) java对数据的操作是通过流的方式. java用于操作流的对象都在IO包中. java IO系统的学习, ...
- java中的File类
File类 java中的File类其实和文件并没有多大关系,它更像一个对文件路径描述的类.它即可以代表某个路径下的特定文件,也可以用来表示该路径的下的所有文件,所以我们不要被它的表象所迷惑.对文件的真 ...
- Java中的文件操作
在使用计算机编程中,常常会用到对于文件的操作,以下是我对于Java中文件的相关内容学习之后的一个总结和在学习过程中遇到的一些问题. 一.什么是文件 对于文件进行操作,首先我们要知道什么是文件.在此之前 ...
- Java中的文件操作(一)RandomAccessFile
今天,学到的是java中的文件操作. Java.IO.File Java中操作文件用到RandomAccessFile类,既可以读取文件内容,也可以向文件输出数据,但不同与普通输入/输出流的是Rand ...
- Java中的IO操作和缓冲区
目录 Java中的IO操作和缓冲区 一.简述 二.IO流的介绍 什么是流 输入输出流的作用范围 三.Java中的字节流和字符流 字节流 字符流 二者的联系 1.InputStreamReader 2. ...
- JAVA中的时间操作
java中的时间操作不外乎这四种情况: 1.获取当前时间 2.获取某个时间的某种格式 3.设置时间 4.时间的运算 好,下面就针对这四种情况,一个一个搞定. 一.获取当前时间 有两种方式可以获得,第一 ...
- java中的集合操作类(未完待续)
申明: 实习生的肤浅理解,如发现有错误之处.还望大牛们多多指点 废话 事实上我写java的后台操作,我每次都会遇到一条语句:List<XXXXX> list = new ArrayList ...
- JAVA中通过Jedis操作Redis连接与插入简单库
一.简述 JAVA中通过Jedis操作Redis连接与插入简单库 二.依赖 <!-- https://mvnrepository.com/artifact/redis.clients/jedis ...
- JAVA中的File.separate(跨平台路径)
转: JAVA中的File.separate(跨平台路径) 2016年03月27日 23:33:50 才不是本人 阅读数:1952 在Windows下的路径分隔符和Linux下的路径分隔符是不一样 ...
随机推荐
- oracle 索引聚簇表的工作原理
作者:Richard-Lui 一:首先介绍一下索引聚簇表的工作原理:(先创建簇,再在簇里创建索引,创建表时指定列的簇类型) 聚簇是指:如果一组表有一些共同的列,则将这样一组表存储在相同的数据库块中:聚 ...
- ios开发将截图保存到相册
- (void)loadImageFinished:(UIImage *)image { UIImageWriteToSavedPhotosAlbum(image, self, @selector(i ...
- Spring Cloud Config 分布式配置管理 5.3
Spring Cloud Config简介 在传统的单体式应用系统中,我们通常会将配置文件和代码放在一起,但随着系统越来越大,需要实现的功能越来越多时,我们又不得不将系统升级为分布式系统,同时也会将系 ...
- SVN还原项目到某一版本(转)
将本地的项目通过SVN还原到某一版本,并将SVN服务器上的项目也还原到这一版本 第一步:新建一个文件夹,如test,选中test右键-checkout到最新版本 第二步:选中test,右键-Torto ...
- 一个命令永久禁用Win10驱动程序强制签名
https://blog.csdn.net/xiaodingqq/article/details/80093888
- 【JS新手教程】replace替换一个字符串中所有的某单词
JS中的replace方法可以替换一个字符串中的单词.语句的格式是: 需要改的字符串.replace(字符串或正则表达式,替换成的字符串) 如果第一个参数用字符串,默认是找到该字符串中的第一个匹配的字 ...
- Eureka客户端源码流程梳理
前面梳理了Eureka服务端的流程,现在整理下客户端的流程. 1.在这个包(spring-cloud-netflix-eureka-client)里面寻找客户端启动入口相关配置,关键配置文件sprin ...
- zookeeper的java api操作
zookeeper的java api操作 创建会话: Zookeeper(String connectString,int sessionTimeout,Watcher watcher) Zookee ...
- {"aa":null} 如何能转化为 {"aa":{}}
一个同事问的一个功能需求:{"aa":null} 如何能转化为 {"aa":{}}因为需求暂时不明确,暂时先完成这样的转换.使用的是FastJson1.2.7 ...
- (模板)hdoj2544(最短路--bellman-ford算法&&spfa算法)
题目链接:https://vjudge.net/problem/HDU-2544 题意:给n个点,m条边,求点1到点n的最短路. 思路: 今天学了下bellman_ford,抄抄模板.dijkstra ...