2014-04-23 2 views
0

제목이 혼란스러운 경우 죄송합니다. 문제는 기본적으로 모듈의 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; 
    } 
} 
+0

질문에 대해 다른 생각을하고 스스로 해결할 수있는 질문을 다시 말할 수 있습니다. 응용 프로그램에서 사용하는 경로를 하드 코딩하지 않고 파일을로드하도록 만들려면 어떻게해야합니까? 아니면 다른 버전이 있습니다 : 어떻게 사용자의 홈 디렉토리를 찾을 수 있습니까? 또는 다른 버전 : 응용 프로그램의 일부로 파일을 저장하고로드하는 방법은 무엇입니까? 실제로 달성하고자하는 것이 무엇인지 모르겠으므로 어떤 대체 질문을해야할지 모르겠습니다. – Gimby

+0

제 3의 것이 가장 정확하다고 생각합니다. 나는 기본적으로 HTML이 작동하는 방식과 유사하기를 원합니다. 프로그램이 동일한 폴더에있는 한 텍스트 파일을로드합니다. 그게 가능하지 않다면, 나는 사용자를위한 디렉토리가 더 좋을 것이라고 생각한다. 어떤 도움을 주셔서 감사합니다 – user3100858

+0

효율성면에서, 각 행을'java.util.List'와 같은 동적 구조에 로딩하고 마지막 단계로'String []'로 변환하는 것이 더 낫습니다. 이렇게하면 파일을 두 번 파싱하지 않아도됩니다. 한 번은 줄 수를 얻고 각 줄을 다시 읽습니다. –

답변

0

할 수있는 일이 두 가지 있습니다.

1) 파일을 사용자가 제공해야하는 경우 위치를 인수로 가져옵니다. 또한 사용자 입력없이 응용 프로그램이 실패하기를 원하면이 방법을 사용하십시오.

public static void main(String... args) { 
    String location = args[0]; 
    ... // Do Stuff 
} 

2) 파일이 정적 인 경우 jar 파일에 패키지하고 리소스로 읽습니다.

public static void main(String... args) { 
    InputStream input = FileClass.getClass().getClassLoader().getResourceAsStream("test.txt") 
    ... // Do Stuff 
} 

속성 파일 인 경우 내 기본 설정은이 둘을 조합 한 것입니다. 기본 속성을 정의하고 패키지화하십시오. 그런 다음 사용자가 자신의 속성을 제공하여 값을 덮어 쓸 수있게합니다. 클래스 패스 (예 2)에서 속성을로드 한 다음 사용자가 제공하는 파일 (예 1)의 값을 모두 바꿉니다.

+0

대단히 도움을 주셔서 감사합니다! – user3100858

관련 문제