Commit b5d7d78b authored by ElaFHNW's avatar ElaFHNW
Browse files

FileIO

parent 95835471
package FilesIO;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalTime;
public class FileWriting {
public static void main(String[] args) {
File f = new File("C:/tmp/mylog.txt");
FileWriter fw;
try {
fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
for (int i=0; i <1000; i++) {
bw.write(LocalTime.now().toString()+ "\n");
}
bw.close();
fw.close();
System.out.println("wrote " + f);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package FilesIO;
// Write a Java program to get a list of all file/directory names
// could extend to solve the problem of importing and renaming
// packages as mentioned by Svetlana at the start of the course
public class ReadDirectory {
public static void main(String[] args) {
// 1. get current directory and print it out
// 2. list all files in the directory
// store all files in an array of files
// 3. print file extensions that exist in the directory
// ignore directories and files that start with .
}
}
package FilesIO;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;
// Write a Java program to get a list of all file/directory names
public class ReadDirectorySolution {
public static void main(String[] args) {
// get current directory
String userDirectory = new File("").getAbsolutePath();
System.out.println("my directory: "+ userDirectory);
// list all files in the directory
// store all files in an array of files
System.out.print("File names: ");
String[] fileList = new File(userDirectory).list();
ArrayList<File> files = new ArrayList<File>();
for (String name:fileList){
System.out.print(name+ " ");
files.add(new File(name));
}
System.out.println();
// print file extensions that exist in the directory
// ignore directories and files that start with.
System.out.print("File extensions: ");
Set <String> ext = new TreeSet<String>();
for (File fi: files) {
if (fi.isDirectory()) {
continue;
}
else if (!fi.getName().startsWith(".") && fi.getName().contains(".")) {
ext.add(fi.getName().split("\\.")[1]);
}
}
System.out.println(ext);
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment