简体   繁体   English

像ls这样的java中的格式化输出

[英]Formated output in java like ls

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. 我需要像在Linux中执行命令ls一样打印它。

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 例如

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM