2014-07-18 2 views
0

먼저 파일 내용을 출력합니다. 여기에 제 코드가 있습니다. 그리고 나서 각 줄을 편집하기 위해 문자열 작업을 할 것입니다. 변경 사항을 저장하려면 어떻게해야합니까? tmp 파일을 만들지 않고도이 작업을 수행 할 수 있습니까?Java에서 파일 내용을 업데이트하는 방법

String executeThis = "cat" + " " + "/var/lib/iscsi/nodes/" 
    + iscsiInfo.selectedTargets2.get(i) + "/" + myString + "/default"; 
String inputThis = ""; 
Process process = ServerHelper.callProcessWithInput(executeThis, inputThis); 

try {   
    logger.debug("stdOutput for editing targets credential:"); 
    BufferedReader stdOutput = new BufferedReader(
    new InputStreamReader(process.getInputStream())); 

    String s = null;   
    while ((s = stdOutput.readLine()) != null) { 
    logger.info("The content [email protected]@@@@@@@@@@@@@@@@@@@@@@@"+s) 
    // do something to edit each line and update the file 
    }   
} catch (IOException e) { 
    logger.fatal(e); 
} 
+1

왜 'FileReader'를 사용하는 대신 프로세스를 실행하고 있습니까? – McLovin

+0

예 파일을 변경하는 동안 스트림을 닫아서이 작업을 수행 할 수 있습니다! – Devavrata

+0

BufferedWriter 사용 http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html. 매번 조언을 끊고 다시 열지 말라. – Kode

답변

2

다음 단계를 수행하면 원하는 결과를 얻을 수 있습니다.

  • tmp 파일을 만들려면 FileWriter 개체를 인스턴스화하십시오.

    FileWriter fw = new FileWriter("tmp"); 
    
  • 원본 파일에서 한 줄씩 읽습니다.

  • 메모리에서이 행 (문자열 객체)을 수정하십시오.

  • 이 문자열을 tmp 파일에 기록합니다.

    fw.write(line); 
    
  • 파일 핸들을 닫습니다.

  • tmp 파일의 이름을 소스 파일 이름으로 바꿉니다.

    sourceFile.renameTo(targetFile); 
    
+0

감사합니다. 원본 파일을 한 줄씩 읽는 방법. FileWriter에서 hasNextLine() 관련 메서드를 찾을 수 없습니다. –

+1

[BufferedWriter.readLine()] (http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()). 네가 인터넷 검색을 해봤 니? – Tim

+0

답변 해 주셔서 감사합니다. 하지만 BufferedWriter가 아닌 BufferedReader.readLine()입니다. –

0

이 질문에 는 here 대답하고있다. 나는 대답을 되풀이한다.

public static void replaceSelected(String replaceWith, String type) { 
    try { 
     // input the file content to the String "input" 
     BufferedReader file = new BufferedReader(new FileReader("notes.txt")); 
     String line;String input = ""; 

     while ((line = file.readLine()) != null) input += line + '\n'; 

     System.out.println(input); // check that it's inputted right 

     // this if structure determines whether or not to replace "0" or "1" 
     if (Integer.parseInt(type) == 0) { 
      input = input.replace(replaceWith + "1", replaceWith + "0"); 
     } 
     else if (Integer.parseInt(type) == 1) { 
      input = input.replace(replaceWith + "0", replaceWith + "1"); 
     } 

     // check if the new input is right 
     System.out.println("----------------------------------" + '\n' + input); 

     // write the new String with the replaced line OVER the same file 
     FileOutputStream File = new FileOutputStream("notes.txt"); 
     File.write(input.getBytes()); 

    } catch (Exception e) { 
     System.out.println("Problem reading file."); 
    } 
} 

public static void main(String[] args) { 
    replaceSelected("Do the dishes","1");  
} 
+0

이것이 OP가 요청한 것이기 때문에 그것이 그가해야 할 일이라는 것을 의미하지는 않습니다. 파일을 편집 할 것이라는 것을 알고있을 때 파일의 각 개별 라인을 외과 적으로 다시 쓰는 것은 좋은 성능이나 깨끗한 프로그램 설계를위한 방법이 아닙니다. – Tim

+0

나는 당신에 동의합니다. 더 나은 해결책은 아니지만 해결책입니다. 나는 그의 질문에 대답한다. 하지만 귀하의 추천은 절대적으로 사실입니다! – Jimmysnn

관련 문제