1: How to reaad text file
public class javareadfile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String line = null;
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
2: How to read and write text files
public class myFile {
public static void main(String[] args) throws IOException{
// write to text file
ArrayList<String> lines = new ArrayList<String>();
lines.add("Сайн уу? world");
lines.add("This is дараагийн мөр");
Path pathtoFile = Paths.get("file.txt");
Files.write(pathtoFile, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
// read from text file
List<String> line2 = Files.readAllLines(pathtoFile, StandardCharsets.UTF_8);
for(String l : line2)
System.out.println(l);
}
}
3: How to copy, move and delete files in Java
public static void main(String[] args) throws IOException{
// write to text file
ArrayList<String> lines = new ArrayList<String>();
lines.add("Сайн уу? world");
lines.add("This is дараагийн мөр");
Path pathtoFile = Paths.get("file.txt");
Files.write(pathtoFile, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
// read from text file
List<String> line2 = Files.readAllLines(pathtoFile, StandardCharsets.UTF_8);
for(String l : line2)
System.out.println(l);
// file exists?
System.out.println("file exists?: " + Files.exists(pathtoFile));
Path pathtoFile2 = Paths.get("file2.txt");
// move file
Files.move(pathtoFile, pathtoFile2, StandardCopyOption.REPLACE_EXISTING);
System.out.println("file exists?: " + Files.exists(pathtoFile));
// copy file
Files.copy(pathtoFile2, pathtoFile);
// delete file
Files.delete(pathtoFile);
Files.delete(pathtoFile2);
}
}
4: How to get free, available and total disk space in Java
public class javadisk {
public static void main(String[] args) throws IOException{
FileStore fs = Files.getFileStore(Paths.get("c:/"));
long totalSpaceInBytes = fs.getTotalSpace();
long freeSpaceInBytes = fs.getUsableSpace();
long usedSpaceInBytes = totalSpaceInBytes - freeSpaceInBytes;
System.out.println("total space in GB: " + (totalSpaceInBytes/1024/1024/1024));
System.out.println("free space in GB: " + (freeSpaceInBytes/1024/1024/1024));
System.out.println("used space in GB: " + (usedSpaceInBytes/1024/1024/1024));
}
}
No comments:
Post a Comment