Java - File

> Procedural Languages > Java > Java - IO (Input/Output) - (File System|File|Console)

1 - About

File - File in Java

Advertising

3 - Management

3.1 - Instantiation

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

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

3.2 - 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 "";
	}
}

3.3 - 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 */ }
Advertising

3.4 - Equality

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

3.5 - 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();

3.6 - 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 
...
lang/java/io/file.txt · Last modified: 2018/06/21 17:04 by gerardnico