首页 > 解决方案 > 我在哪里将我的文件位置插入到此代码中?

问题描述

我有这段代码可以读取文件并将内容作为字符串返回,但我不知道将文件路径或位置放在哪里

C:\Users\johnm\eclipse-workspace\W4A6\src\input.in

任何帮助都会很棒。

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Encryption {

    public static String readFile(String filename) throws IOException {
        Scanner scanner = new Scanner(new File(filename));
        String content = "";
        while (scanner.hasNextLine()) {
            content += scanner.nextLine();
        }
        return content;
    }
}

标签: javastringfile

解决方案


问:我在哪里放置文件路径或位置?

A:谁调用readFile()Encryption类的方法,谁就确定文件路径名。

一种常见的技术是“静态主”,并将文件路径作为命令行参数传递。

例子:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Encryption {

    public static String readFile(String filename) throws IOException {
        Scanner scanner = new Scanner(new File(filename));
        String content = "";
        while (scanner.hasNextLine()) {
            content += scanner.nextLine();
        }
        return content;
    }

    public static void main (String[] args) {
        if (args.length != 1) {
            System.out.println("Please enter a filepath");
        } else {
            Encryption.readFile(args[0]);
        }
    }
}

或者,您可以从 GUI 调用 Encryption.readFile()。或来自网络服务。

无论如何:调用者应该始终“知道”文件路径,并将其作为参数传递给 readFile()。


推荐阅读