2012-05-18 4 views
3

자바 문자열 변수에 파일 내용이 있습니다.이 문자열을 File 개체로 변환하고 싶습니다.자바에서 String을 File Object로 변환하는 방법은 무엇입니까?

public void setCfgfile(File cfgfile) 
{ 
    this.cfgfile = cfgfile 
} 

public void setCfgfile(String cfgfile) 
{ 
    println "ok overloaded function" 
    this.cfgfile = new File(getStreamFromString(cfgfile)) 
} 
private def getStreamFromString(String str) 
{ 
    // convert String into InputStream 
    InputStream is = new ByteArrayInputStream(str.getBytes()) 
    is 
} 
+0

음, 당신이 달성하고자하는 것을 말씀해 주시겠습니까? 왜 File 객체입니까? 이해할 수 있을지 모르겠다. – Ewald

+0

@ 에얼드 : 이것은 [이] 계속됩니다 (http://stackoverflow.com/questions/10639819/how-to-upload-a-file-using-apache-commons-file-upload-from-a-servlet) – abi1964

+0

나는 아래에 2 개의 대답이있다, 나는 더 많은 것을 가진 포스트를 오염시키지 않을 것이다! – Ewald

답변

7

, 당신과 함께 다른 두 답변을 단순화 할 수 있습니다 : 그것은 단지

+1

+1 그것을 얻는 것은 멋져요! –

+0

@tim_yates : 'XmlSlurper'를 제외하고는 모두'잘 빠져 있습니다. '라는 메시지가 나옵니다.'치명적 오류 'E : % 5CTomcat % 206 % 5Cbin % 5C .. % 5Cwebapps % 5Ccsm % 5Cfiles % 5C1-105101 % 5Cac onsole1_csmagentinhyundai_9. 1.xml : 1 : 1 : 내용이 프롤로그에서 허용되지 않습니다. org.xml.sax.SAXParseException : 내용이 프롤로그에서 허용되지 않습니다. XML의 첫 번째 줄은 '> – abi1964

+0

잘못된 XML이라고 가정합니다. 그럼 파일에 쓰고 있니? 당신은 그것을 보았습니까? 파일에 쓰기 전에 XmlSlurper를 문자열에서 바로 읽을 수 있습니까? –

0

당신은 항상 File(String) 생성자를 사용하여 String에서 File 개체를 만들 수 있습니다. File 객체는 추상 경로 이름 만 나타냅니다. 디스크에있는 파일이 아닙니다.

당신은 당신이 사용할 수있는 몇 가지 클래스 예를 들어, 거기에 문자열에 의해 개최 된 텍스트가 포함 된 디스크에있는 실제 파일 만들려고하는 경우 :

try { 
    Writer f = new FileWriter(nameOfFile); 
    f.write(stringToWrite); 
    f.close(); 
} catch (IOException e) { 
    // unable to write file, maybe the disk is full? 
    // you should log the exception but printStackTrace is better than nothing 
    e.printStackTrace(); 
} 

FileWriter 때 플랫폼의 디폴트 인코딩을 사용하는 것 문자열의 문자를 디스크에 쓸 수있는 바이트로 변환합니다. 이것이 문제인 경우 OutputStreamWriter 안에 FileOutputStream을 래핑하여 다른 인코딩을 사용할 수 있습니다. 예를 들어 :

private writeToFile(String content) { 
    BufferedWriter bw; 
    try { 
     bw = new BufferedWriter(new FileWriter(this.cfgfile)); 
     bw.write(content); 
    } 
    catch(IOException e) { 
     // Handle the exception 
    } 
    finally { 
     if(bw != null) { 
      bw.close(); 
     } 
    } 
} 

는 게다가, new File(filename) 단순히 (이름 filename으로 새로운 File 객체를 instanciates

는하지 않습니다 :

String encoding = "UTF-8"; 
Writer f = new OutputStreamWriter(new FileOutputStream(nameOfFile), encoding); 
0

파일에 String를 작성하려면 보통 BufferedWriter 사용해야합니다 실제로 디스크에 파일을 만듭니다). 따라서 문 다음 이름 this.cfgfile = new File(getStreamFromString 메소드에 의해 반환되는 String

this.cfgfile = new File(getStreamFromString(cfgfile)) 

것이다 간단한 실체화 새로운 File. 이 그루비이므로

2

content를 쓴 파일에 파일 핸들을 반환합니다

File writeToFile(String filename, String content) { 
    new File(filename).with { f -> 
    f.withWriter('UTF-8') { w -> 
     w.write(content) 
    } 
    f 
    } 
} 

apache commons io LIB

를 사용해보십시오
org.apache.commons.io.FileUtils.writeStringToFile(File file, String data) 
관련 문제