Table of Contents

About

File - File in Java

Management

Object Instantiation

The file corresponding to the file name might not even exist.

File f = new File("myFileName.txt");

Creation

with the nio library

Path path = Paths.get("target/example.txt");
Files.createFile(path);

Read

FileReader fileReader = new FileReader(file);
FileReader fileReader = new FileReader(path.toFile());
  • With encoding
new InputStreamReader(new FileInputStream(filePath), encoding)

Write

BufferedWriter writer = Files.newBufferedWriter(path, Charset.UTF8, StandardOpenOption.APPEND)

Get the file extension

static private String getFileExtension(Path path) {
	String name = path.getFileName().toString();
	try {
		return name.substring(name.lastIndexOf(".") + 1);
	} catch (Exception e) {
		return "";
	}
}

Meta Information

Path myFile = Paths.get("D:\\temp\\temp.txt");
System.out.println("The file exists ?: "+Files.exists(myFile));
System.out.println("The file size in bytes is: "+Files.size(myFile));
System.out.println("The file is a regular file? : "+Files.isRegularFile(myFile));
System.out.println("The file is readable? : "+Files.isReadable(myFile));
System.out.println("The file is executable? : "+Files.isExecutable(myFile));
The file exists ?: true
The file size in bytes is: 13346941
The file is a regular file? : true
The file is readable? : true
The file is executable? : true

if(f.exists()) { /* do something */ }
if(f..isFile()) { /* do something */ }

Equality

System.out.println("The file and the directory are equal? : "+Files.isSameFile(myFile, myDirectory));
The file and the directory are equal? : false

From file to string

with Java - Java IO

import org.apache.commons.io.IOUtils;
FileInputStream in = new FileInputStream(files[i]);
String sqlStatement = IOUtils.toString(in);
in.close();

Temporary

// Write the final in the Java directory system property ''java.io.tmpdir''
File tempFile = File.createTempFile(prefix, suffix)

String tempDir = System.getProperty("java.io.tmpdir");

# see also:
Files.createTempFiles 
...