【发布时间】:2014-06-08 12:47:05
【问题描述】:
对不起,如果标题令人困惑。问题是我基本上需要将我的 java 程序放在 CD 上的模块上,我想知道如何设置目录以便它可以在没有“C://Users/Haf/Desktop/test.txt”的情况下工作。文本文件”。以下是使用的两个类(不确定您是否都需要):
package javaapplication2;
import java.io.*;
import javax.swing.JOptionPane;
/**
*
* @author Haf
*/
public class FileClass {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
String file_name = "C://Users/Haf/Desktop/test.txt";
try {
ReadFile file = new ReadFile(file_name);
String [] aryLines = file.OpenFile();
int i;
for (i=0; i < aryLines.length; i++) {
System.out.println(aryLines[i]);
}
}
catch (IOException e) {
System.out.println(e.getMessage () );
}
}
}
。
package javaapplication2;
import java.io.*;
public class ReadFile { //creating a constructor
private String path;
public ReadFile(String file_path) {
path = file_path;
}
public String[] OpenFile() throws IOException { //returning a string array. You need to use IOException
FileReader fr = new FileReader (path); //creating FileReader obj called fr
BufferedReader textReader = new BufferedReader(fr); //bufferedreader obj
int numberOfLines = readLines();
String [] textData = new String[numberOfLines]; //array length set by numberOfLines
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader (file_to_read);
String aLine;
int numberOfLines = 0;
while (( aLine = bf.readLine()) !=null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
【问题讨论】:
-
我可以改写您的问题,这可能会让您也有不同的想法并自己解决:如何使应用程序用于加载文件的路径不被硬编码?或者这里是另一个版本:我怎样才能找到用户的主目录?或者另一个版本:我如何存储和加载文件作为我的应用程序的一部分?我不知道你想要真正实现什么,所以我不知道我必须回答哪个替代问题。
-
我想第三个是最准确的。我基本上希望它类似于 HTML 的工作方式,只要它们在同一个文件夹中,程序就会加载文本文件。如果那不可能,我想为用户找到目录会更好。感谢您的帮助
-
效率方面,您最好将每一行加载到动态结构中,例如
java.util.List,然后将其转换为String[]作为最后一步。这将避免您必须解析文件两次 - 一次获取行数,再次读取每一行