【问题标题】:Console shows only the file-name and content of file together instead of only content控制台只显示文件的文件名和内容,而不是只显示内容
【发布时间】:2019-07-15 16:47:31
【问题描述】:

我想显示文件内容的预览。但不幸的是,名称与内容一起显示。我不知道如何打印它的内容。这是一个字符串方法,所以它必须回馈一些东西。而且我不能把它变成一个 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...

【问题讨论】:

  • 自己调用showPreview(f, 7),这样就不会打印函数的返回值了。
  • 工作。谢谢!

标签: java file


【解决方案1】:

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

代码行:

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

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

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

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

// 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]);
}

【讨论】:

  • 非常感谢您抽出宝贵时间回答我的问题!我真的很感激。你的例子对我帮助很大!谢谢!!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-23
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多