당신은 항상 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);
음, 당신이 달성하고자하는 것을 말씀해 주시겠습니까? 왜 File 객체입니까? 이해할 수 있을지 모르겠다. – Ewald
@ 에얼드 : 이것은 [이] 계속됩니다 (http://stackoverflow.com/questions/10639819/how-to-upload-a-file-using-apache-commons-file-upload-from-a-servlet) – abi1964
나는 아래에 2 개의 대답이있다, 나는 더 많은 것을 가진 포스트를 오염시키지 않을 것이다! – Ewald