简体   繁体   English

如何扫描和打印文件内容?

[英]How do I make a file's contents scanned and printed?

Using java, I need to make a program that asks the user which file to scan, and to do some work with the data in the file. 使用java,我需要编写一个程序来询问用户要扫描的文件,并对文件中的数据进行一些处理。

My program is supposed to select a file, scan the file for a specific character that the user specifies, and return with how many specific characters there are in that file. 我的程序应该选择一个文件,在文件中扫描用户指定的特定字符,然后返回该文件中有多少个特定字符。

This is my code so far: 到目前为止,这是我的代码:

import java.io.*;
import java.util.Scanner;

public class CharSearch {
    public static void main(String[] args) throws Exception{

    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter the name of the file you want to search.");
    String fileInput = scanner.nextLine();

    System.out.println("What character would you like to look for in " + fileInput + "?");

    Scanner fileScanner = new Scanner(fileInput);
    System.out.println(fileScanner);
    }
}

I imported io and scanner, then set up the scanner to read which file the user inputs. 我导入了io和扫描仪,然后设置了扫描仪以读取用户输入的文件。 I print back out that file name. 我打印出该文件名。 The last two lines are where I need help. 最后两行是我需要帮助的地方。 How can I make the scanner return with the data in the file. 如何使扫描仪返回文件中的数据。

There is a file in my folder called data.txt and all that is written in it is "dataWord." 我的文件夹中有一个名为data.txt的文件,其中写入的都是“ dataWord”。 For starters, I want the scanner to read the file and the program to display dataWord, but its not working. 对于初学者,我希望扫描仪读取文件并显示dataWord的程序,但无法正常工作。 I am a rookie, so please work with me. 我是新秀,所以请和我一起工作。 Thanks. 谢谢。

Instead of passing path of file as String pass it as a File 而不是将文件的路径作为String传递,而将其作为File传递

    Scanner fileScanner = new Scanner(new File(fileInput));
    while (fileScanner.hasNext()) {
        System.out.println(fileScanner.next());
    }
    scanner.close();
    fileScanner.close();

If the file is an external file or not in your project, you can specify the absolute path of file. 如果文件是外部文件,或者不在您的项目中,则可以指定文件的绝对路径

If it is in classpath you can read using ClassLoader 如果它在类路径中,则可以使用ClassLoader读取

     java.io.InputStream inputStream = this.getClassLoader().getResourceAsStream("file_path")

Scanner has a constructor with InputStream 扫描仪具有InputStream的构造函数

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

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