控制台仅显示文件名和文件内容,而不显示内容

时间:2019-07-15 16:47:31

标签: java file

我想显示文件内容的预览。但不幸的是,名称与内容一起显示。我不知道如何仅打印其内容。这是一个字符串方法,因此必须回馈一些东西。而且我不能将其转换为void方法,因为它必须在System.out.println中打印,而void方法不能在System.our.printlns中打印,您可能知道。所以,你能帮我吗?

搜索“ //文件预览仅显示文件名,但不显示其内容。为什么?!”您将直接找到错误的位置。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FilesInfo {

    File datei = new File(
            "C:\\Users\\Elias\\Desktop\\ALLE_ORDNER\\Elias\\BACKUPKOMPLETT\\Uni Kram\\Uni Köln\\Informationsverarbeitung\\WS 2018.2019\\Java 1\\HA10");

    public static void main(String[] args) {

        FilesInfo main = new FilesInfo();
        main.printDirInfo(
                "C:\\Users\\Elias\\Desktop\\ALLE_ORDNER\\Elias\\BACKUPKOMPLETT\\Uni Kram\\Uni Köln\\Informationsverarbeitung\\WS 2018.2019\\Java 1\\HA10");

    }

    public void printDirInfo(String dirPath) {

        File dir = new File(dirPath);
        if (dir.isDirectory()) {

            if (dir.list().length <= 0) {
                System.out.println("Is empty!");
            }

            System.out.println("Direction " + dir.getName() + "  contains " + dir.listFiles().length
                    + "  Files/Directions:");

        }

        else {
            System.out.println(dir + " ist kein Verzeichnis!");
        }

        // Die einzelnen File-Objekte aus dem Verzeichnis "dir"
        for (File f : dir.listFiles()) {


//File preview shows name of file together with some content.. How can I solve this problem?
            System.out.println("File " + f.getName() + " | File preview: " + showPreview(f, 7) + "...");
        }

    }

    private String showPreview(File f, int laenge) {
        String name;

        try {

            String line;
            BufferedReader br = new BufferedReader(new FileReader(f));
            if ((line = br.readLine()) != null) {

                System.out.println("the content preview " + line.substring(0, 5) + "...");
                System.out.println();

            }
        } catch (FileNotFoundException e) {

            System.err.println("It seems that there is no file!!");
        } catch (IOException e) {
            System.err.println("An error has occured while loading!");
        }

        name = f.getName().substring(0, laenge);
        return name;

//  private String showFileName() {
//      
//      for(dir: )
//  }

    }
}

console:


Direction HA10  contains 3  Files/Directions:
the content preview Java ...

File java-short.txt | File preview: java-sh...
the content preview Ein R...

File raabe.txt | File preview: raabe.t...
the content preview Dies ...

File test.txt | File preview: test.tx...

1 个答案:

答案 0 :(得分:0)

我认为通常来说,在文本文件内容的开头显示5个字符并不能真正起到预览作用,尤其是如果第一行包含多个空格或全部为空白。如果您或您的一个应用程序正在创建这些文件,并且文件的前5个字符被视为标识字符,则这当然会有所不同。在文件创建和内容放置中已应用了特定的规则,因此只需要5个字符即可。

代码行:

System.out.println("File " + f.getName() + " | File preview: " + showPreview(f, 7) + "...");

有点令人担忧。您需要记住,正在写入控制台的 showPreview()方法中的任何内容都将在显示上一行之前进入控制台。该方法本身还返回一个文件名,该文件名使用String#substring()方法被截断(laenge = length):

name = f.getName().substring(0, laenge);

我不认为您希望这种情况发生。我相信您要返回的是实际的预览文本。我也认为您不希望showPreview()方法在控制台中显示任何内容,至少在这种情况下,您不应该这样做。此方法的 laenge (长度)参数实际上是用来提供所需的预览长度的,这是正确的。您可能希望在控制台中显示的内容如下:

// The ShowPreview() method is passed 18 for length argument
File: java-short.txt | File Preview: This is info on sh...
File: raabe.txt | File Preview: Info on the raabe ...
File: test.txt | File Preview:  Test file for this...

现在,我当然可以错了,但是如果是这种情况,那么您的方法在看起来像这样的情况下可能会更好一些:

private String showPreview(File f, int length) {
    String previewText = "";
    String line;
    /* Try With Resourses is used to auto-close the reader. You should
       always close opened files when you're done with them.        */
    try (BufferedReader br = new BufferedReader(new FileReader(f))) {
        while ((line = br.readLine()) != null) {
            line = line.trim(); // Trim of leading/trailing whitespaces or tabs, etc.
            // Skip blank lines (if any).
            if (line.equals("")) {
                continue;
            }
            /* Grab first line with actual text but first make sure 
               there is enough text to satisfy the supplied desired 
               length otherwise an exception will be thrown by the 
               substring() method.                               */
            if (line.length() < length) {
                length = line.length();
            }
            previewText = line.substring(0, length) + "...";
            break; // Only need the first bit of content so get outta here.
        }
    }
    catch (FileNotFoundException ex) {
        previewText = "FILE NOT FOUND!";
    }
    catch (IOException ex) {
        previewText = "ERROR READING FILE!";
    }

    // If the actual file contains no preview content.
    if (previewText.equals("")) {
        previewText = "FILE IS EMPTY!";
    }
    /* Return the aquired preview text from file or
       any error that may have occurred.          */
    return previewText; 
}

下面,我提供了另一种方法来完成相同的任务,不同之处在于,它允许您提供搜索文件的目录路径(它还探索该路径中的子目录)。它还允许您提供您只想处理的文件扩展名的String []数组(提供 null 处理所有文件)。最后,它允许您提供一个整数值以指示文件内容预览的大小(以字符为单位)。文件中仅文本的第一行实际用于预览,因此,如果您提供的值是34323(例如,运气不佳),则只会得到文件中的第一行实际文本(除非没有换行符在文件中。)

这是方法:

/**
 * Displays a file preview within the Console Window.<br><br>
 * 
 * @param folderPath       (String) The full path to the folder to search in. 
 *                         All Sub-directories will also be searched.<br>
 * 
 * @param fileTypeFilter   (String[] Array) Here you would supply a String
 *                         array of the file name extensions you would like
 *                         to process (Search for). If null is supplied or 
 *                         a zero length String[] Array then ALL files are 
 *                         processed in the supplied Folder path and any sub-
 *                         folders contained within it. Each extension added 
 *                         to the array may or may not contain the dot so, 
 *                         either ".txt" or "txt" is considered valid.<br>
 *
 * @param previewCharCount (Integer) The number of characters long the preview 
 *                         text should be.<br>
 *
 * @return (String[] Array) All the file paths found.
 */
public String[] folderFilesPreview(String folderPath, String[] fileTypeFilter, int previewCharCount) {
    String ps = File.separator;
    // Gather up the desired files to preview...
    File folder = new File(folderPath);
    String[] filesAndFoldersList = folder.list();
    if (filesAndFoldersList == null || filesAndFoldersList.length == 0) {
        return null;
    }
    List<String> desiredFilesList = new ArrayList<>();
    for (String file : filesAndFoldersList) {
        File f = new File(folder.getAbsolutePath() + ps + file);
        if (f.isDirectory()) {
            // A sub-folder is detected. Use recursion.
            String[] fafl2 = folderFilesPreview(f.getPath(), fileTypeFilter, previewCharCount);
            if (fafl2 != null && fafl2.length != 0) {
                desiredFilesList.addAll(Arrays.asList(fafl2));
            }
        }
        else {
            if (fileTypeFilter != null && fileTypeFilter.length > 0 && hasFileNameExtension(f.getAbsolutePath())) {
                boolean isInFilterList = false;
                for (String extension : fileTypeFilter) {
                    extension = !extension.startsWith(".") ? "." + extension : extension;
                    String fileExt = file.substring(file.lastIndexOf("."));
                    if (fileExt.equalsIgnoreCase(extension)) {
                        isInFilterList = true;
                        break;
                    }
                }
                if (isInFilterList) {
                    desiredFilesList.add(f.getAbsolutePath());
                }
            }
            else {
                desiredFilesList.add(f.getAbsolutePath());
            }
        }
    }

    for (int i = 0; i < desiredFilesList.size(); i++) {
        String file = desiredFilesList.get(i);
        String fileName = file.substring(file.lastIndexOf(File.separator) + 1);
        // Read each file and display the preview...
        String previewText = "";
        // Try With Resourses is used to auto-close the reader.
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.trim().equals("")) {
                    continue;
                }
                previewText+= line.trim().length() >= previewCharCount
                        ? line.trim().substring(0, previewCharCount) + "..."
                        : line.trim().substring(0) + "...";
                break;
            }

            // If there is no content found in file...
            if (previewText.equals("")) {
                previewText = "FILE IS EMPTY!";
            }
        }
        catch (FileNotFoundException ex) {
            previewText = "FILE NOT FOUND!";
        }
        catch (IOException ex) {
            previewText = "ERROR READING FILE!";
        }
        System.out.println("File: " + fileName + " | File preview: " + previewText);
    }
    return desiredFilesList.toArray(new String[0]);
}