제목이 혼란스러운 경우 죄송합니다. 문제는 기본적으로 모듈의 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;
}
}
질문에 대해 다른 생각을하고 스스로 해결할 수있는 질문을 다시 말할 수 있습니다. 응용 프로그램에서 사용하는 경로를 하드 코딩하지 않고 파일을로드하도록 만들려면 어떻게해야합니까? 아니면 다른 버전이 있습니다 : 어떻게 사용자의 홈 디렉토리를 찾을 수 있습니까? 또는 다른 버전 : 응용 프로그램의 일부로 파일을 저장하고로드하는 방법은 무엇입니까? 실제로 달성하고자하는 것이 무엇인지 모르겠으므로 어떤 대체 질문을해야할지 모르겠습니다. – Gimby
제 3의 것이 가장 정확하다고 생각합니다. 나는 기본적으로 HTML이 작동하는 방식과 유사하기를 원합니다. 프로그램이 동일한 폴더에있는 한 텍스트 파일을로드합니다. 그게 가능하지 않다면, 나는 사용자를위한 디렉토리가 더 좋을 것이라고 생각한다. 어떤 도움을 주셔서 감사합니다 – user3100858
효율성면에서, 각 행을'java.util.List'와 같은 동적 구조에 로딩하고 마지막 단계로'String []'로 변환하는 것이 더 낫습니다. 이렇게하면 파일을 두 번 파싱하지 않아도됩니다. 한 번은 줄 수를 얻고 각 줄을 다시 읽습니다. –