Java의 기존 파일에 텍스트를 추가하는 방법
-
06-07-2019 - |
문제
Java의 기존 파일에 텍스트를 반복적으로 추가해야합니다. 어떻게해야하나요?
해결책
로깅 목적으로 이것을하고 있습니까? 그렇다면 있습니다 이를위한 여러 라이브러리. 가장 인기있는 두 가지가 있습니다 log4J 그리고 로그백.
Java 7+
한 번만해야한다면 파일 클래스 이것을 쉽게 만듭니다 :
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
주의 깊은: 위의 접근법은 a NoSuchFileException
파일이 아직 존재하지 않는 경우 또한 Newline을 자동으로 추가하지 않습니다 (텍스트 파일에 추가 할 때 자주 원하는). 스티브 챔버스의 대답 이 작업을 수행 할 수있는 방법을 다룹니다 Files
수업.
그러나 동일한 파일에 여러 번 쓸면 위의 위는 디스크의 파일을 여러 번 열고 닫아야합니다. 이는 느린 작동입니다. 이 경우 완충 작가가 더 좋습니다.
try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
메모:
- 두 번째 매개 변수
FileWriter
생성자는 새 파일을 작성하지 않고 파일에 추가하도록 지시합니다. (파일이 존재하지 않으면 생성됩니다.) - 사용 a
BufferedWriter
고가의 작가에게 권장됩니다 (예 :FileWriter
). - 사용 a
PrintWriter
액세스 할 수 있습니다println
아마도 당신이 익숙한 구문System.out
. - 하지만
BufferedWriter
그리고PrintWriter
포장지는 엄격하게 필요하지 않습니다.
더 오래된 자바
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
예외 처리
구형 Java에 대한 강력한 예외 처리가 필요하면 매우 장점이 있습니다.
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
다른 팁
당신이 사용할 수있는 fileWriter
깃발이 설정되어 있습니다 true
, 추가.
try
{
String filename= "MyFile.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write("add a line\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
Try/Catch 블록이있는 모든 답변이 마지막 블록에 포함 된 .close () 조각이 없어야합니까?
표시된 답변 예 :
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
out.println("the text");
} catch (IOException e) {
System.err.println(e);
} finally {
if (out != null) {
out.close();
}
}
또한 Java 7 기준으로 시도-자원 문서를 시도하십시오. 선언 된 자원이 자동으로 처리되므로 선언 된 리소스를 폐쇄하는 데 최종적으로 블록이 필요하지 않으며, 또한 장점이 적기 때문입니다.
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
out.println("the text");
} catch (IOException e) {
System.err.println(e);
}
편집하다 -Apache Commons 2.1 기간 동안 올바른 방법은 다음과 같습니다.
FileUtils.writeStringToFile(file, "String to append", true);
마지막으로 파일을 올바르게 닫는 것을 포함하도록 @kip의 솔루션을 조정했습니다.
public static void appendToFile(String targetFile, String s) throws IOException {
appendToFile(new File(targetFile), s);
}
public static void appendToFile(File targetFile, String s) throws IOException {
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(targetFile, true)));
out.println(s);
} finally {
if (out != null) {
out.close();
}
}
}
약간 확장합니다 KIP의 대답, 여기에 간단한 Java 7+ 방법이 있습니다. 새로운 라인 파일에 아직 존재하지 않으면 생성합니다:
try {
final Path path = Paths.get("path/to/filename.txt");
Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
// Add your own exception handling...
}
메모: 위는 다음을 사용합니다 Files.write
쓰여진 과부하 윤곽 파일에 대한 텍스트 (예 : println
명령). 끝까지 텍스트를 작성하려면 (즉, print
명령), 대안 Files.write
바이트 어레이를 통과하는 과부하를 사용할 수 있습니다 (예 : "mytext".getBytes(StandardCharsets.UTF_8)
).
모든 시나리오에서 스트림이 제대로 닫히도록하십시오.
오류가 발생한 경우 파일 핸들을 열어 두는이 답변 수는 약간 놀라운 일입니다. 대답 https://stackoverflow.com/a/15053443/2498188 돈에 있지만 그 때문입니다 BufferedWriter()
던질 수 없습니다. 그렇다면 예외가 떠날 것입니다 FileWriter
객체가 열립니다.
이 작업을 수행하는보다 일반적인 방법은 BufferedWriter()
던질 수 있습니다 :
PrintWriter out = null;
BufferedWriter bw = null;
FileWriter fw = null;
try{
fw = new FileWriter("outfilename", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
finally{
try{
if( out != null ){
out.close(); // Will close bw and fw too
}
else if( bw != null ){
bw.close(); // Will close fw too
}
else if( fw != null ){
fw.close();
}
else{
// Oh boy did it fail hard! :3
}
}
catch( IOException e ){
// Closing the file writers failed for some obscure reason
}
}
편집하다:
Java 7 기준으로 권장되는 방법은 "리소스와 함께 시도"를 사용하고 JVM이이를 다루게하는 것입니다.
try( FileWriter fw = new FileWriter("outfilename", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)){
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
Java-7에서도 그런 종류를 수행 할 수 있습니다.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
//---------------------
Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);
Java 7+
나는 평범한 자바의 팬이기 때문에 겸손한 견해로는 그것이 앞서 언급 한 답변의 조합이라고 제안 할 것입니다. 어쩌면 나는 파티에 늦었을 것입니다. 코드는 다음과 같습니다.
String sampleText = "test" + System.getProperty("line.separator");
Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
파일이 존재하지 않으면 파일이 생성되고 이미 존재하면 추가됩니다.샘플 텍스트 기존 파일에. 이것을 사용하면 클래스 경로에 불필요한 libs를 추가하지 못하게됩니다.
이것은 한 줄의 코드로 수행 할 수 있습니다. 도움이 되었기를 바랍니다 :)
Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);
java.nio 사용.파일 java.nio.file과 함께.표준 균형
PrintWriter out = null;
BufferedWriter bufWriter;
try{
bufWriter =
Files.newBufferedWriter(
Paths.get("log.txt"),
Charset.forName("UTF8"),
StandardOpenOption.WRITE,
StandardOpenOption.APPEND,
StandardOpenOption.CREATE);
out = new PrintWriter(bufWriter, true);
}catch(IOException e){
//Oh, no! Failed to create PrintWriter
}
//After successful creation of PrintWriter
out.println("Text to be appended");
//After done writing, remember to close!
out.close();
이것은 a를 만듭니다 BufferedWriter
수락하는 파일 사용 StandardOpenOption
매개 변수 및 자동 플러싱 PrintWriter
결과에서 BufferedWriter
. PrintWriter
'에스 println()
그런 다음 메소드를 호출하여 파일에 쓸 수 있습니다.
그만큼 StandardOpenOption
이 코드에 사용 된 매개 변수 : 작성을 위해 파일을 엽니 다. 파일에만 추가되며 파일이 존재하지 않는 경우 파일을 만듭니다.
Paths.get("path here")
교체 할 수 있습니다 new File("path here").toPath()
. 그리고 Charset.forName("charset name")
원하는 것을 수용하도록 수정할 수 있습니다 Charset
.
작은 세부 사항을 추가합니다.
new FileWriter("outfilename", true)
2.nd 매개 변수 (true)는 호출 된 기능 (또는 인터페이스)입니다. 추가 가능한 (http://docs.oracle.com/javase/7/docs/api/java/lang/appendable.html). 특정 파일/스트림 끝에 일부 컨텐츠를 추가 할 수 있어야합니다. 이 인터페이스는 Java 1.5 이후에 구현됩니다. 각 물체 (즉, Bufferedwriter, Charraywriter, Charbuffer, Filewriter, 필터 라이터, Logstream, OutputStreamWriter, PipedWriter, PrintStream, Printwriter, Stringbuffer, StringBuilder, StringWriter, Writer)이 인터페이스와 함께 콘텐츠 추가에 사용될 수 있습니다.
즉, GZIPPEN 파일 또는 일부 HTTP 프로세스에 콘텐츠를 추가 할 수 있습니다.
구아바를 사용한 샘플 :
File to = new File("C:/test/test.csv");
for (int i = 0; i < 42; i++) {
CharSequence from = "some string" + i + "\n";
Files.append(from, to, Charsets.UTF_8);
}
BufferFileWriter를 사용해보십시오.
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
bufferFileWriter.append(obj.toJSONString());
bufferFileWriter.newLine();
bufferFileWriter.close();
} catch (IOException ex) {
Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
String str;
String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new FileWriter(path, true));
try
{
while(true)
{
System.out.println("Enter the text : ");
str = br.readLine();
if(str.equalsIgnoreCase("exit"))
break;
else
pw.println(str);
}
}
catch (Exception e)
{
//oh noes!
}
finally
{
pw.close();
}
이것은 당신이 의도 한 일을 할 것입니다 ..
Try-With-Resources를 사용하는 것이 좋습니다.
static void appendStringToFile(Path file, String s) throws IOException {
try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
out.append(s);
out.newLine();
}
}
우리가 Java 7 이상을 사용하고 있고 또한 우리가 사용할 수있는 파일에 추가 (추가) 할 내용을 알고 있다면 신생 작가 NIO 패키지의 메소드.
public static void main(String[] args) {
Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
String text = "\n Welcome to Java 8";
//Writing to the file temp.txt
try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
주목해야 할 사항은 몇 가지 있습니다.
- Charset Encoding을 지정하는 것은 항상 좋은 습관이며, 우리는 수업 시간에 일정합니다.
StandardCharsets
. - 코드가 사용됩니다
try-with-resource
시도 후 자원이 자동으로 닫히는 명세서.
OP는 요청하지 않았지만 특정 키워드를 가진 줄을 검색하고 싶지만 예를 들어 confidential
Java에서 스트림 API를 사용할 수 있습니다.
//Reading from the file the first line which contains word "confidential"
try {
Stream<String> lines = Files.lines(FILE_PATH);
Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
if(containsJava.isPresent()){
System.out.println(containsJava.get());
}
} catch (IOException e) {
e.printStackTrace();
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Writer {
public static void main(String args[]){
doWrite("output.txt","Content to be appended to file");
}
public static void doWrite(String filePath,String contentToBeAppended){
try(
FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)
)
{
out.println(contentToBeAppended);
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
}
}
FileOutputStream stream = new FileOutputStream(path, true);
try {
stream.write(
string.getBytes("UTF-8") // Choose your encoding.
);
} finally {
stream.close();
}
그런 다음 업스트림 어딘가에 ioexception을 잡습니다.
프로젝트의 어느 곳에서나 기능을 만들고 필요한 곳에서 해당 기능을 호출하십시오.
여러분은 당신이 비동기 적으로 부르지 않는 능동적 인 스레드를 부르고 있다는 것을 기억해야합니다. 프로젝트에 더 많은 시간을 보내고 이미 작성된 글을 쓰는 것을 잊어 버리십시오. 제대로
//Adding a static modifier would make this accessible anywhere in your app
public Logger getLogger()
{
return java.util.logging.Logger.getLogger("MyLogFileName");
}
//call the method anywhere and append what you want to log
//Logger class will take care of putting timestamps for you
//plus the are ansychronously done so more of the
//processing power will go into your application
//from inside a function body in the same class ...{...
getLogger().log(Level.INFO,"the text you want to append");
...}...
/*********log file resides in server root log files********/
코드 2 라인은 실제로 세 번째 이후 실제로 텍스트를 추가합니다. :피
도서관
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
암호
public void append()
{
try
{
String path = "D:/sample.txt";
File file = new File(path);
FileWriter fileWriter = new FileWriter(file,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
fileWriter.append("Sample text in the file to append");
bufferFileWriter.close();
System.out.println("User Registration Completed");
}catch(Exception ex)
{
System.out.println(ex);
}
}
당신은 또한 이것을 시도 할 수 있습니다 :
JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file
try
{
RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
long length = raf.length();
//System.out.println(length);
raf.setLength(length + 1); //+ (integer value) for spacing
raf.seek(raf.length());
raf.writeBytes(Content);
raf.close();
}
catch (Exception e) {
//any exception handling method of ur choice
}
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);
True는 기존 파일의 데이터를 추가 할 수 있습니다. 우리가 글을 쓰면
FileOutputStream fos = new FileOutputStream("File_Name");
기존 파일을 덮어 씁니다. 그러니 첫 번째 접근 방식으로 가십시오.
나는 제안 할 것이다 아파치 커먼즈 프로젝트. 이 프로젝트는 이미 필요한 작업을 수행하기위한 프레임 워크 (예 : 컬렉션의 유연한 필터링)를 제공합니다.
다음 방법은 일부 파일에 텍스트를 추가하겠습니다.
private void appendToFile(String filePath, String text)
{
PrintWriter fileWriter = null;
try
{
fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(
filePath, true)));
fileWriter.println(text);
} catch (IOException ioException)
{
ioException.printStackTrace();
} finally
{
if (fileWriter != null)
{
fileWriter.close();
}
}
}
대안 적으로 사용합니다 FileUtils
:
public static void appendToFile(String filePath, String text) throws IOException
{
File file = new File(filePath);
if(!file.exists())
{
file.createNewFile();
}
String fileContents = FileUtils.readFileToString(file);
if(file.length() != 0)
{
fileContents = fileContents.concat(System.lineSeparator());
}
fileContents = fileContents.concat(text);
FileUtils.writeStringToFile(file, fileContents);
}
효율적이지는 않지만 잘 작동합니다. 라인 브레이크는 올바르게 처리되고 아직 존재하지 않으면 새 파일이 작성됩니다.
이 코드는 귀하의 필요를 충족시킬 것입니다.
FileWriter fw=new FileWriter("C:\\file.json",true);
fw.write("ssssss");
fw.close();
당신이 원한다면 특정 줄에 텍스트를 추가하십시오 먼저 전체 파일을 읽고 원하는 곳에 텍스트를 추가 한 다음 아래 코드와 같은 모든 것을 덮어 쓸 수 있습니다.
public static void addDatatoFile(String data1, String data2){
String fullPath = "/home/user/dir/file.csv";
File dir = new File(fullPath);
List<String> l = new LinkedList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
String line;
int count = 0;
while ((line = br.readLine()) != null) {
if(count == 1){
//add data at the end of second line
line += data1;
}else if(count == 2){
//add other data at the end of third line
line += data2;
}
l.add(line);
count++;
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
createFileFromList(l, dir);
}
public static void createFileFromList(List<String> list, File f){
PrintWriter writer;
try {
writer = new PrintWriter(f, "UTF-8");
for (String d : list) {
writer.println(d.toString());
}
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
내 대답 :
JFileChooser chooser= new JFileChooser();
chooser.showOpenDialog(chooser);
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";
try
{
RandomAccessFile random = new RandomAccessFile(file, "rw");
long length = random.length();
random.setLength(length + 1);
random.seek(random.length());
random.writeBytes(Content);
random.close();
}
catch (Exception exception) {
//exception handling
}
/**********************************************************************
* it will write content to a specified file
*
* @param keyString
* @throws IOException
*********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
// For output to file
File a = new File(textFilePAth);
if (!a.exists()) {
a.createNewFile();
}
FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(keyString);
bw.newLine();
bw.close();
}// end of writeToFile()
Follong 코드를 사용하여 파일의 내용을 추가 할 수 있습니다.
String fileName="/home/shriram/Desktop/Images/"+"test.txt";
FileWriter fw=new FileWriter(fileName,true);
fw.write("here will be you content to insert or append in file");
fw.close();
FileWriter fw1=new FileWriter(fileName,true);
fw1.write("another content will be here to be append in the same file");
fw1.close();
1.7 접근 :
void appendToFile(String filePath, String content) throws IOException{
Path path = Paths.get(filePath);
try (BufferedWriter writer =
Files.newBufferedWriter(path,
StandardOpenOption.APPEND)) {
writer.newLine();
writer.append(content);
}
/*
//Alternative:
try (BufferedWriter bWriter =
Files.newBufferedWriter(path,
StandardOpenOption.WRITE, StandardOpenOption.APPEND);
PrintWriter pWriter = new PrintWriter(bWriter)
) {
pWriter.println();//to have println() style instead of newLine();
pWriter.append(content);//Also, bWriter.append(content);
}*/
}