Java에서 텍스트 필드의 텍스트가 <text" 라는 문자열 변수에 있습니다.
텍스트 변수의 내용을 파일에 저장하려면 어떻게 해야 하나요?
PrintWriter out = new PrintWriter("filename.txt");
그런 다음, 이를 통해 만들 때처럼, 어떤 문자열 출력 스트림을:
out.println(text);
자바 7 이상을 사용하는 경우, a href = " < " 사용할 수 있습니다;;;;;; " /a> statement< 자원을 사용하여 시도하시겠습니까 >, https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" '네' 가 자동으로 프린츠트림 닫으십시오 완료했으면 (ie 를 종료하십시오 블록) 이 같은 있습니다.
try (PrintWriter out = new PrintWriter("filename.txt")) {
out.println(text);
}
여전히 '이전과 같이 명시적으로 자바드리오스피리노푸네스세페시옹' 할 수 있습니다.
아파치 커먼즈 입출력 (i / o) map_layer 피레티우스 에는 다음과 같은 몇 가지 좋은 방법, 특히 이 일을 하는 방법:
static void writeStringToFile(File file, String data)
쓸 수 있는 텍스트 파일로 한 메서드 호출:
FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
이 파일의 인코딩입니다 specifying 고려해야 할 수도 있습니다 잘 알려져 있다.
제 프로젝트에서도 비슷한 작업을 수행했습니다. FileWriter]1를 사용하면 작업의 일부가 단순화됩니다. 그리고 여기에서 좋은 튜토리얼을 찾을 수 있습니다.
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)
{
}
}
자바 가상 머신 (jvm) 에 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
아래 코드를 작성하기 위한 수정하십시오 에서 파일을 사용할 수 있습니다 있는모든 클래스나 함수 () 는 취급료 텍스트는. The world needs a 표시되어도 왜 궁금해 한 새로운 텍스트 편집기를.
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();
}
}
}
Files.writeString(Path.of("my", "path"), "My String");
둘째, 이 방법 (지켜보리니 JavaDoc [here] [2]) 개별 글자셋 지정할 수 있습니다.
Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);
옵션 설정 파일 처리 방법이 모두 선택적 바라리스 매개변수입니다 (http://otl. JavaDoc here). 다음 예제에서는 문자열을 만들어 갈 것 "이라고 존재하지 않는 파일 또는 덮어쓰기/추가 기존 1:
Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
[1]: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html # 라이티스트링 (,, 자바드니오가르세스카르세 자바드니오피리드패스 자바드프랑스카르지케노스 자바드니오필레지오프누티언스) [2]: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html # 라이티스트링 (, 자바드프랑스카르지케노스 자바드니오피리드패스 자바드니오필레지오프누티언스) [3]: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/charset/StandardCharsets.html # UTF_8
텍스트 파일을 만들 경우 기반으로 하는 경우 하나의 문자열:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class StringWriteSample {
public static void main(String[] args) {
String text = "This is text to be saved in file";
try {
Files.write(Paths.get("my-file.txt"), text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
아파치 커먼즈 입출력 api 를 사용하여. 그 간단한
Api 로 사용
FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");
메이븐 상관 관계
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
저는 가능하면 엔드입니다 포지셔닝하십시오 라이브러리보다는 이용할 수 있는 일종의 운영할 수 있다. 따라서 중요한 단계인 실수로 생략하십시오 날 가능성이 적다 (볼프스니페스 같은 실수를 브라운아저씨의 참조). 하지만 일부 라이브러리는 그들위에 제안됩니다 내가 가장 좋아하는 것은 이러한 형태의 구글 구아바. 파일 는 클래스 불렀으매 구아바 아주 잘 작동하는 이 작업:
// This is where the file goes.
File destination = new File("file.txt");
// This line isn't needed, but is really useful
// if you're a beginner and don't know where your file is going to end up.
System.out.println(destination.getAbsolutePath());
try {
Files.write(text, destination, Charset.forName("UTF-8"));
} catch (IOException e) {
// Useful error handling here
}
import java.io.*;
private void stringToFile( String text, String fileName )
{
try
{
File file = new File( fileName );
// if file doesnt exists, then create it
if ( ! file.exists( ) )
{
file.createNewFile( );
}
FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
BufferedWriter bw = new BufferedWriter( fw );
bw.write( text );
bw.close( );
//System.out.println("Done writing to " + fileName); //For testing
}
catch( IOException e )
{
System.out.println("Error: " + e);
e.printStackTrace( );
}
} //End method stringToFile
이 방법을 를 클래스뿐만 삽입할 수 있습니다. 이 방법을 사용하는 경우 이 방법을 통해 기본 클래스에서 변경하십시오 정적 클래스의 정적 추가하기만 키워드다. 그렇지 않으면 파일을 사용할 수 있도록 했다고 합니다 (java.io) 에서 제공합니다.* 어느 쪽이든 가져오기할 필 라이터 및 부퍼드라이터 인식할 수 없습니다.
Java 를 사용하여 '7':
public static void writeToFile(String text, String targetFilePath) throws IOException
{
Path targetPath = Paths.get(targetFilePath);
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Files.write(targetPath, bytes, StandardOpenOption.CREATE);
}
이 작업을 수행할 수 있었습니다.
import java.io.*;
import java.util.*;
class WriteText
{
public static void main(String[] args)
{
try {
String text = "Your sample content to save in a text file.";
BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
out.write(text);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
return ;
}
};
텍스트 파일로 덮어쓰여집니다 경우에만 이 때마다 한 블록 신경을 쓰고 있다.
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
FileOutputStream stream = null;
PrintStream out = null;
try {
File file = chooser.getSelectedFile();
stream = new FileOutputStream(file);
String text = "Your String goes here";
out = new PrintStream(stream);
out.print(text); //This will overwrite existing contents
} catch (Exception ex) {
//do something
} finally {
try {
if(stream!=null) stream.close();
if(out!=null) out.close();
} catch (Exception ex) {
//do something
}
}
}
이 예에서는 chooser 파일을 사용하여 파일을 선택할 수 있습니다.
private static void generateFile(String stringToWrite, String outputFile) {
try {
FileWriter writer = new FileWriter(outputFile);
writer.append(stringToWrite);
writer.flush();
writer.close();
log.debug("New File is generated ==>"+outputFile);
} catch (Exception exp) {
log.error("Exception in generateFile ", exp);
}
}
내가 생각하는 가장 좋은 방법은 '피레스트라이트 사용하고 (경로 경로, Iterable<,? 연장시킵니다 CharSequence>. 선, 오픈포션. 옵션) '.
String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));
[Javadoc] 참조 (https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html # 쓰기 (, % % 자바드니오피리드패스 20java.lang.iterable 20java.nio.charset.charset 20java.nio.file.openoption., %):
>. 쓰기 흐름선 텍스트 파일로. 각 행은 챨 e0100042.log 있다 >. 파일 기록됩니까 순서에 따라 각 줄이 종료되었습니다. >. # 39, s 라인 분리자를 platform& 의해 정의된 대로 시스템 등록 >. 라인트제프라토리 문자를 사용하여 지정된 인코딩됩니다 salesforce. 바이트입니다 >. 문자세트. >. >. 옵션 매개변수입니다 생성되거나 열릴 파일을 지정합니다. >. 이 방법은 없는 경우 그 생성 옵션 networkr. 것처럼, >. 옵션 및 쓰기 truncate_existing networkr. 즉, >. 이 경우, t # 39 doesn& 열었든 파일에 쓰기 위해 존재하지 않거나, 파일 작성 >. 처음에는 기존 일반 파일 크기로 자르기 0 입니다. 이 >. 그동안 모든 방법을 사용하면 파일 닫힐 줄 때 >. 서면 (호스트였든 I / O 또는 기타 런타임 예외 오류가 발생합니다.) 경우 >. 그 후 또는 파일 창조하 승인하십시오 i/o 오류가 발생할 수 있습니다. >. 그동안 일부 바이트입니다 깎은 후 또는 기록됩니까 절실해졌습니다.
참고. # 39 에 내장된 ',' 내가 보고 있는 사람들이 이미 답변됨 Java& 피레스트라이트 what& 있지만, s # 39 는 어떤 특별한 내 오토메이티드 아니예 언급하십시오 과부하된 버전의 메서드로부터 는 이트레이블 카르지케노스 있는 것 (즉, 문자열), [] '의' 대신 ' ()' 가 필요 없는 바이트입니다 어레이이며 카타시안 테스트스제비츠, 이는 좀 더 좋은 것 같네요.