About
Sitemap in Java
Management
Object Instantiation
The file corresponding to the file name might not even exist.
- In the Java nio model, a file is uniquely identified by a path object.
- In Java - Java IO, file instances represent file or directory names.
File f = new File("myFileName.txt");
Creation
with the nio library
Path path = Paths.get("target/example.txt");
Files.createFile(path);
Read
- FileReader use the default encoding.
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
- with Java - (Nio|New I/O) Package, you access the file system with the Files class
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
- with Java - Java IO
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
...