2013-01-22 3 views
0

방금 ​​프로그래밍을 시작했으며 Java에서 기본 파일 I/O 프로그램을 만드는 동안 막혔습니다.파일에서 문자열을 대체하는 방법은 무엇입니까?

사용 사례 : 파일의 문자열을 확인하고 같은 줄에 문자열을 추가하고 싶습니다. E.G. 다음과 같이 파일 내용은 다음과 같습니다

hostname=localhost 
port=192 

그래서, 내 프로그램은 위의 파일에서 hostname 문자열을보고 나는 그것을 전달할 지금까지 어떤 값으로 localhost를 교체합니다.

파일을 가져 와서 내용을 임시 파일로 전달할 수 있지만 파일에서 문자열을 조작하는 방법을 알 수 없습니다. 어떤 도움을 주셔서 감사합니다.

+2

에 경우

당신은 당신이 이미 가지고있는 몇 가지 코드를 보여줄 수 있습니까? –

+1

['Properties'] (http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html) API를 사용하십시오. –

답변

0

여기 당신이 그것을 할 수있는 방법 (오류/예외 처리 및 인수로 대상 및 교체를 거치지 않고 기본) 두 가지 방법이 있습니다. 가장 좋은 방법보다는 파일을 저장 키/값 쌍은 사용자 java.util.Properties

public class ReplaceInFile { 

    private final static String src = "test.txt"; 
    private final static String dst_str = "test_new_str.txt"; 
    private final static String dst_prop = "test_new_prop.txt"; 

    public static void main(String[] args) throws IOException { 
     usingStringOperations(); 
     usingProperties(); 
    } 

    private static void usingProperties() throws IOException { 
     File srcFile = new File(src); 
     FileInputStream fis = new FileInputStream(srcFile); 
     Properties properties = new Properties(); 
     properties.load(fis); 
     fis.close(); 
     if(properties.getProperty("hostname") != null) { 
      properties.setProperty("hostname", "127.0.0.1"); 
      FileOutputStream fos = new FileOutputStream(dst_prop); 
      properties.store(fos, "Using java.util.Properties"); 
      fos.close(); 
     } 
    } 

    private static void usingStringOperations() throws IOException { 
     File srcFile = new File(src); 
     FileInputStream fis = new FileInputStream(srcFile); 
     int len = fis.available(); 
     if(len > 0) { 
      byte[] fileBytes = new byte[len]; 
      fis.read(fileBytes, 0, len); 
      fis.close(); 
      String strContent = new String(fileBytes); 
      int i = strContent.indexOf("localhost"); 
      if(i != -1) { 
       String newStrContent = strContent.substring(0, i) + 
         "127.0.0.1" + 
         strContent.substring(i + "localhost".length(), strContent.length()); 
       FileOutputStream fos = new FileOutputStream(dst_str); 
       fos.write(newStrContent.getBytes()); 
       fos.close();  
      } 
     } 
    } 
} 
1

당신은 String.replace()을 시도 할 수 :

String replacement = "you-other-host"; 

// Read your file line by line... 
line = line.replace("localhost", replacement); 
// and write the modified line to your temporary file 
관련 문제