„Java“ yra du pagrindiniai būdai patikrinti, ar yra failas ar katalogas. Šitie yra:
1 - Files.exists
iš NIO paketo
2 - File.exists
iš seno IO paketo
Pažiūrėkime keletą pavyzdžių iš kiekvieno paketo.
Kodas naudoja Path
ir Paths
iš „Java NIO“ paketo, kad patikrintumėte, ar yra failas:
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CheckFileExist {
public static void main(String[] args) {
Path path = Paths.get('/path/to/file/app.log');
if (Files.exists(path)) {
if (Files.isRegularFile(path)) {
System.out.println('App log file exists');
}
} else {
System.out.println('App log file does not exists');
}
} }
Panašiai, jei norėtume patikrinti, ar „Java“ yra katalogas, naudodamas NIO paketą:
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CheckDirectoryExist {
public static void main(String[] args) {
Path path = Paths.get('/path/to/logs/');
if (Files.exists(path)) {
if (Files.isDirectory(path)) {
System.out.println('Logs directory exists');
}
} else {
System.out.println('Logs directory does not exist');
}
} }
Jei nenaudojate „Java NIO“ paketo, galite naudoti seną „Java IO“ paketą:
import java.io.File; public class CheckFileExists {
public static void main(String[] args) {
File file = new File('/path/to/file/app.log');
if(file.exists()) {
System.out.println('App log file exists');
} else {
System.out.println('App log file does not exist');
}
} }
Panašiai, norėdami patikrinti katalogą, galime naudoti:
import java.io.File; public class CheckFileExists {
public static void main(String[] args) {
File file = new File('/path/to/logs/');
if(file.isDirectory()) {
System.out.println('Logs directory exists');
} else {
System.out.println('Logs directory does not exist');
}
} }
Papildoma literatūra