2017-12-16 10 views
1

これはファイルの内容を削除して書き込みを行うコードです コンテンツを削除せずにファイルに書き込む最後の行ファイルの内容を削除せずにjavaでテキストファイルを書き込む方法

import java.io.*; 
import java.util.Scanner; 

public class SetValues { 

    public void setNumberPhone(String numberPhone) throws UnsupportedEncodingException { 
     Scanner input = new Scanner(System.in); 
     PrintWriter pr = null; 

     try { 
      input = new Scanner("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt"); 
      pr = new PrintWriter("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt", "UTF-8"); 

     } catch (FileNotFoundException e) { 
      System.out.println("Not Open" + e.getMessage()); 
      System.exit(0); 
     } 

     if (input.hasNext()) { 
      pr.println(numberPhone); 
     } 
     pr.close(); 

    } 
} 
+0

ファイル出力ストリームを使用するとどうなりますか? – Lokesh

+1

これを読む - https://stackoverflow.com/questions/13741751/modify-the-content-of-a-file-using-java – ric

+0

Java 7以降を使用している場合は、https:// docsを使用できます。 oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio。 file.OpenOption ...-。 'StandardOption.APPEND'を追加するオプション – Veera

答えて

1
import java.nio.file.Files; 
import java.nio.file.Paths; 
import java.io.*; 

OutputStream os = Files.newOutputStream(Paths.get("C:/Users/Abdalrahman/Desktop/PhoneNumber.txt"), APPEND); 
PrintWriter pr = new PrintWriter(os); 

pr.println("TEXT"); 

これは、任意の出力テキストは、ファイルの現在の内容に追加されますここで出力ストリームを作成します。 OutputStreamを使用してPrintWriterを作成できます。詳細については、at the Java documentation

関連する問題