I have list of names of files and directories in directory for example:
List<String> list = new ArrayList<Strings>(); /* list of files */
and I need to print it like command ls in linux do that.
a.txt file1.txt filewithverylongname.txt Folder1
g.txt G_longfile2.txt h.txt i.txt
Number of columns depends on number of files and size of columns depends on length of each file or directory name in same column. If I know number of files I would use something in in this link but the number of files or directories could be variable .. How can I do it?
To get number of files in folder
File file = new File("D:\\AnyFolder");
if(file.isDirectory()) {
File[] listFiles = file.listFiles();
System.out.println("Total files in folder : " + listFiles.length );
}
I believe this would satisfy your requirement:
import java.io.File;
public class Ls {
private static final int NUM_COLUMNS = 3;
private static final int SEPARATING_SPACE_LENGTH = 2;
public static void main(String[] args) {
File file = new File("C:/WINDOWS");
if(file.isDirectory()) {
File[] listFiles = file.listFiles();
list(listFiles);
}
}
private static void list(File[] files) {
int[] maxLength = new int[NUM_COLUMNS];
for (int i = 0; i < files.length; i++) {
int fileLength = files[i].getName().length();
int columnIndex = i % NUM_COLUMNS;
if (maxLength[columnIndex] < fileLength) {
maxLength[columnIndex] = fileLength;
}
}
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
System.out.print(fileName);
for (int j = 0; j < maxLength[i % NUM_COLUMNS] - fileName.length() + SEPARATING_SPACE_LENGTH; j++) {
System.out.print(" ");
}
if ((i + 1) % NUM_COLUMNS == 0) {
System.out.print("\n");
}
}
}
}
Let me know if it's not clear.
Thanks,
EG
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.