java - 我在哪里将我的文件位置插入到此代码中?
问题描述
我有这段代码可以读取文件并将内容作为字符串返回,但我不知道将文件路径或位置放在哪里
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;
}
}
解决方案
问:我在哪里放置文件路径或位置?
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()。
推荐阅读
- javascript - 如何在javascript中本地保存树视图节点
- javascript - 尝试通过使用javascript单击图像来设置图像的不透明度,但不断出现错误
- angular - 谷歌地图地方请求只返回一个地方
- amazon-web-services - 使用 cloudFormation 将角色附加到现有 EC2 实例
- angular - 从对象数组的 ng-For 循环内动态地将纬度和经度传递给角度谷歌地图
- python - 如果 x,y 在坐标框内
- magento - 使用 XAMPP 安装 Magento 2.3 时出错。无法打开本地主机/演示网站
- javascript - 如何使用 getJSON 读取和显示 json 二维数组?
- c# - 无法将类型“UnityEngine.ScriptableObject”隐式转换为“T”
- wordpress - Gutenberg Block RichText 元素在编辑器中双重显示