Java读取文本文件
我有一个关于Java中txt文件的问题 当我必须阅读文本文件时,我必须指出路径 但是,txt文件位于同一文件夹中 我们需要做的是 正在测试读取选项文件名 测试:类名 readoption:用于读取文件的选项 filename:同一文件夹的文件名 但是,我不想使用path来指出文件,这意味着我想在代码中不使用“C:/Users/myname/Desktop/myfolder/”来读取文本文件 有人知道怎么做吗 谢谢Java读取文本文件,java,readfile,fileinputstream,Java,Readfile,Fileinputstream,我有一个关于Java中txt文件的问题 当我必须阅读文本文件时,我必须指出路径 但是,txt文件位于同一文件夹中 我们需要做的是 正在测试读取选项文件名 测试:类名 readoption:用于读取文件的选项 filename:同一文件夹的文件名 但是,我不想使用path来指出文件,这意味着我想在代码中不使用“C:/Users/myname/Desktop/myfolder/”来读取文本文件 有人知道怎么做吗 谢谢 public class testing{ private static
public class testing{
private static boolean debug = true;
public static void main(String args [])
{
if(args.length == 0)
{// if you do nothing
if(debug == true)
{
System.out.println(args);
}
System.err.println("Error: Missing Keywords");
return;
}
else if(args.length == 1)
{// if you miss key word
if(debug == true)
{
System.out.println(args);
}
System.err.println("Error: Missing filename");
return;
}
else
{// if it is fine
String pathes = "C:/Users/myname/Desktop/myfolder/";// dont want to use this part
if(debug == true)
{
System.out.println("Everthing is fine");
System.out.println("Keyword :" + args[0]);
System.out.println("File name :" + args[1]);
}
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(pathes + "bob.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
}
如果将文本文件放入java项目中的“myfolder”中,则路径应如下所示:
String pathes = "/myfolder/bob.txt";
FileInputStream fstream = new FileInputStream(pathes);
从.properties文件加载文件的路径(使用
java.util.properties
类),或从命令行(在main
String[]
参数中)将其作为参数传递
无论哪种方式,处理文件的代码都不能这样做,必须在外部完成。您的处理代码从调用它的方法接收文件路径,因此如果您决定使用另一种方法(例如GUI),则无需更改。更改此行
String paths=“C:/Users/myname/Desktop/myfolder/”代码>至:
String pathes = args[1];
FileInputStream fstream = new FileInputStream(pathes);
这一行FileInputStream fstream=newfileinputstream(paths+“bob.txt”)代码>至:
String pathes = args[1];
FileInputStream fstream = new FileInputStream(pathes);
您可以使用“.”作为实际路径,并添加依赖于系统的文件分隔符,如:
FileInputStream fstream = new FileInputStream("."+System.getProperty("file.separator")+"bob.txt");
我们可以不使用“/myfolder/bob.txt”吗?我的意思是我只想使用bob.txt。嗯……你可以。如果您只是在项目中创建一个bob.txt文件(不将文件放入文件夹),我将bob.txt文件放入src文件夹,因此jave文件和txt文件现在位于同一文件夹中..好的,但是您的路径必须是“src/bob.txt”,我们可以不使用“/myfolder/bob.txt”吗?我的意思是我只想使用bob.txt。我把bob.txt文件放在同一个文件夹中folder@DcRedwing:嗯?我告诉您替换对myfolder
或bob.txt
的任何引用。为什么只在args中传递名称?为什么不走过整条路呢?文件的内容是什么?它是应用程序资源吗?信息是否需要用户编辑?