Java에서는 “text”라는 String 변수에 텍스트 필드의 텍스트가 있습니다.
“text”변수의 내용을 파일로 저장하려면 어떻게해야합니까?
답변
이진 데이터가 아닌 단순히 텍스트를 출력하는 경우 다음이 작동합니다.
PrintWriter out = new PrintWriter("filename.txt");
그런 다음 출력 스트림과 마찬가지로 문자열을 작성하십시오.
out.println(text);
언제나처럼 예외 처리가 필요합니다. out.close()
쓰기가 끝나면 전화하십시오 .
Java 7 이상을 사용하는 경우 ” try-with-resources 문 “을 사용 PrintStream
하면 다음과 같이 완료했을 때 자동으로 닫힙니다 (예 : 블록 종료).
try (PrintWriter out = new PrintWriter("filename.txt")) {
out.println(text);
}
여전히 java.io.FileNotFoundException
이전 과 같이 명시 적으로 던져야합니다 .
답변
Apache Commons IO 에는이를 수행하기위한 몇 가지 훌륭한 방법이 있으며 특히 FileUtils에는 다음과 같은 방법이 있습니다.
static void writeStringToFile(File file, String data)
한 번의 메소드 호출로 파일에 텍스트를 쓸 수 있습니다.
FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
파일 인코딩을 지정하는 것도 고려할 수 있습니다.
답변
Java File API를 살펴보십시오
간단한 예 :
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(text);
}
답변
Java 7에서는 다음을 수행 할 수 있습니다.
String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());
여기에 더 많은 정보가 있습니다 :
http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403
답변
내 프로젝트에서 비슷한 것을했습니다. FileWriter 를 사용 하면 작업의 일부를 단순화 할 수 있습니다. 그리고 여기 당신은 좋은 튜토리얼을 찾을 수 있습니다 .
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter( yourfilename));
writer.write( yourstring);
}
catch ( IOException e)
{
}
finally
{
try
{
if ( writer != null)
writer.close( );
}
catch ( IOException e)
{
}
}
답변
Apache Commons IOFileUtils.writeStringToFile()
에서 사용합니다 . 이 특정 바퀴를 재발 명할 필요가 없습니다.
답변
아래 코드 수정을 사용하여 텍스트를 처리하는 클래스 또는 함수에서 파일을 쓸 수 있습니다. 왜 세상에 새로운 텍스트 편집기가 필요한지 궁금합니다 …
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
String str = "SomeMoreTextIsHere";
File newTextFile = new File("C:/thetextfile.txt");
FileWriter fw = new FileWriter(newTextFile);
fw.write(str);
fw.close();
} catch (IOException iox) {
//do stuff with exception
iox.printStackTrace();
}
}
}