【问题标题】:Where do I insert my file location into this code?我在哪里将我的文件位置插入到此代码中?
【发布时间】:2021-12-04 23:50:27
【问题描述】:

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

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;
    }
}

【问题讨论】:

    标签: java string file


    【解决方案1】:

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

    答:谁调用你的Encryption 类的readFile() 方法将确定文件路径名。

    一种常用技术是“static main”,并将文件路径作为命令行参数传递。

    示例:

    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()。

    【讨论】:

      【解决方案2】:

      到目前为止,您只定义了一个读取具有给定文件名的文件的方法。
      你需要使用你想要的文件路径来调用它,所以在你的情况下:

      String content = Encryption.readFile("C:\\Users\\johnm\\eclipse-workspace\\W4A6\\src\\input.in");
      

      【讨论】:

      • 这仅在 OP 对 string literal 进行硬编码时才重要,并且仅当字符串文字恰好包含 Windows“\”分隔符时才重要。如果程序接受来自用户输入的路径名(例如命令行或文本小部件):没问题。如果路径使用正斜杠分隔符(“/”) - 没问题。小花絮:大多数文件 I/O 函数在 Windows 上将接受 EITHER 正斜杠或反斜杠路径分隔符 - 没关系。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多