2013-11-09 3 views
8

여기에 소스를 읽었으니 &이지만 다음 코드는 작동하지 않습니다. 기본적으로 'src'폴더에서 'Administrator'라는 텍스트 파일을 읽고 싶습니다. 이 프로젝트는 다른 사람에게 이전 될 수 있으므로 상대 경로가 필요합니다. 제발 저를 참아주십시오.텍스트 파일 상대 경로를 읽는 방법

public void staffExists() throws IOException 
    {    
     //http://stackoverflow.com/questions/2788080/reading-a-text-file-in-java 
     BufferedReader reader = new BufferedReader(new FileReader(getClass().getResourceAsStream ("/DBTextFiles/Administrator.txt"))); 

     try 
     {    
      String line = null; 
      while ((line = reader.readLine()) != null) 
      { 
       if (!(line.startsWith("*"))) 
       { 
        System.out.println(line); 
       } 
      } 

     } 
     catch (IOException ex) 
     { 
      ex.printStackTrace(); 
     }    

     finally 
     { 
      reader.close(); 
     }   
    } 
+2

의 중복 가능성 [프로젝트에서 상대 경로에서 텍스트 파일을 읽는 방법?] (http://stackoverflow.com/questions/3844307/how-to-read-text-file-from-relative- path-in-a-project) –

+1

문제점은 무엇입니까? –

+0

@Dooby Inc : 제안 된 URL을 살펴 봤습니다. 그러나 나는 아직도 그것을 작동시킬 수 없다. 친절하게 나를 인도 해주세요. – user2945412

답변

16

이 유효한 절대 경로 (시스템에 제가 알고)입니다 :

/path/to/directory/../../otherfolder/etc/ 
그래서

other answer가 한 말과 현재 디렉토리의 경로를 얻을 수 있었다 :

filePath.concat("path to the property file"); 
:
String filePath = new File("").getAbsolutePath(); 

다음으로 상대 경로를 연결할

1

이 올바르지 않습니다 :

new FileReader(getClass().getResourceAsStream ("/DBTextFiles/Administrator.txt")) 

당신이 원하는 :

new InputStreamReader(getClass().getResourceAsStream ("/DBTextFiles/Administrator.txt")) 
+0

이 정확하지 왜 설명하기 좋을 것이다. 감사. –

+0

형식 검사를하지 않습니다. –

0

거의 모든 경우에 당신이 휴대용 앞으로이 모든 경우에 "/"." 슬래시 사용해야 당신이를 받아들이는 파일 생성자 중 하나를 사용해야합니다 파일 (부모) & 문자열 (파일 이름) 또는 사용 System.getProperty("file.separator").

10

이제 다소 대답을 얻을 수 있습니다. & getti에 도움이됩니다. 나를 목표로 삼아 라. 내 코드 &에 대한 짧은 편집이 효과가 있었습니까? 희망을 가지고 가난한 영혼을 도울 수 있기를 바랍니다.

String filePath = new File("").getAbsolutePath(); 
System.out.println (filePath); 

//http://stackoverflow.com/questions/2788080/reading-a-text-file-in-java  
//http://stackoverflow.com/questions/19874066/how-to-read-text-file-relative-path 
BufferedReader reader = new BufferedReader(new FileReader(filePath + "/src/DBTextFiles/Administrator.txt")); 

try 
{       
    String line = null;   
    while ((line = reader.readLine()) != null) 
    { 
     if (!(line.startsWith("*"))) 
     { 
      System.out.println(line); 
     } 
    }    
} 
catch (IOException ex) 
{ 
    ex.printStackTrace(); 
}    

finally 
{ 
    reader.close(); 
}     
관련 문제