回答:
ロギング目的でこれを行っていますか?もしそうなら、このためのいくつかのライブラリがあります。最も人気のある2つはLog4jとLogbackです。です。
これを一度だけ実行する必要がある場合は、Filesクラスを使用すると簡単です。
try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}注意:上記の方法ではNoSuchFileException、ファイルがまだ存在しない場合にaがスローされます。また、改行を自動的に追加することもありません(テキストファイルに追加するときによく必要になります)。Steve Chambersの答えは、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コンストラクタ新しいファイルを書き込むのではなく、ファイルに追加するように指示します。(ファイルが存在しない場合は作成されます。)BufferedWriterは、高価なライター(FileWriter)にます。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
    }
}new BufferedWriter(...)例外がスローされることを想像してみましょう。ウィルFileWriter閉鎖されますか?close()メソッドは(通常の状態で)outオブジェクトで呼び出されるため、閉じられないと思います。この場合、初期化されないため、close()メソッドは呼び出されません->ファイルは開かれますが、閉鎖されません。だから私見はtryステートメントがこのようになるはずです    try(FileWriter fw = new FileWriter("myFile.txt")){ Print writer = new ....//code goes here }  そして彼はブロックをflush()抜ける前に作家でなければなりませtryん!!!
                    StandardOpenOption.APPEND作成しないでください。例外をスローしないため、サイレントエラーのようなものです。(2)を使用.getBytes()すると、付加されたテキストの前後に改行文字がありません。これらに対処するための代替回答を追加しました。
                    追加するために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(FileWriter fw = new FileWriter(filename,true)){ // Whatever }catch(IOException ex){ ex.printStackTrace(); } 
                    ここでtry / catchブロックを使用したすべての回答で、finallyブロックに.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-with-resourcesステートメントを使用できます。宣言されたリソースを閉じるためにfinallyブロックは必要ありません。自動的に処理されるため、冗長性も低くなります。
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
}outスコープ外になることがガベージコレクション、権利を取得するとき、それは自動的に閉じていますか?finallyブロックの例では、私がout.close()正しく覚えていれば、実際には別の入れ子のtry / catchが必要だと思います。Java 7ソリューションは非常に洗練されています。(私はJava 6以降Java開発を行っていないので、その変更に慣れていませんでした。)
                    flush方法が必要ですか?
                    編集 -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を書き込むオーバーロードを使用しています(つまり、コマンドに似ています)。末尾にテキストを書き込むだけ(つまり、コマンドと同様)には、バイト配列(たとえば)を渡して別のオーバーロードを使用できます。printlnprintFiles.write"mytext".getBytes(StandardCharsets.UTF_8)
.CREATEはあなたのために仕事をすると思った。
                    エラーが発生した場合に、これらの回答のうちいくつがファイルハンドルを開いたままにしておくかは、少し憂慮すべきことです。答え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.
  }PrintWriter.close()でdocsのようthrows IOExceptionに宣言されていません。ソースを見ると、close()メソッドは実際にはをスローできません。IOExceptionこれは、基礎となるストリームからメソッドをキャッチし、フラグを設定しているためです。したがって、次のスペースシャトルまたはX線線量測定システムのコードに取り組んでいる場合は、PrintWriter.checkError()を試してから使用する必要がありますout.close()。これは本当に文書化されているはずです。
                    XX.close()はそれぞれ独自のトライ/キャッチにすべきですよね?例えば、out.close()その場合には、例外をスローする可能性bw.close()とfw.close()呼ばれることはありません飽きないだろう、とfw近くに最も重要なものです。
                    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以降
私はプレーンJavaのファンなので、控えめな意見では、前述の回答を組み合わせたものだと思います。多分私はパーティーに遅れる。これがコードです:
 String sampleText = "test" +  System.getProperty("line.separator");
 Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8), 
 StandardOpenOption.CREATE, StandardOpenOption.APPEND);ファイルが存在しない場合は作成し、すでに存在する場合はsampleTextを既存のファイルに追加し ます。これを使用すると、クラスパスに不要なライブラリを追加する必要がなくなります。
java.nioを使用する。java.nio.fileと一緒のファイル。StandardOpenOption
    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();これにより、パラメーター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パラメータは、機能(又は、インタフェース)と呼ばれる追記(http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html)。特定のファイル/ストリームの最後にコンテンツを追加できるようにする責任があります。このインターフェースはJava 1.5以降に実装されています。このインターフェイスを持つ各オブジェクト(つまり、BufferedWriter、CharArrayWriter、CharBuffer、FileWriter、FilterWriter、LogStream、OutputStreamWriter、PipedWriter、PrintStream、PrintWriter、StringBuffer、StringBuilder、StringWriter、Writer)は、コンテンツの追加に使用できます
つまり、gzipファイルにコンテンツを追加したり、httpプロセスを追加したりできます。
Guavaを使用したサンプル:
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.appendで試してください。
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を使用するよりも、Java 7以前のすべてのビジネスを使用する方が良い
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パッケージのnewBufferedWriterメソッドを利用できます。
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();
    }
}注意すべき点がいくつかあります。
StandardCharsetsます。try-with-resource、試行後にリソースが自動的に閉じられるステートメントを使用します。OPは尋ねていませんが、特定のキーワードを持つ行を検索する場合に備えて、たとえばconfidentialJavaでストリーム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();
}write(String string)場合、各文字列が書き込まれた後にnewLine()
                    FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);trueの場合、既存のファイルにデータを追加できます。書くなら
FileOutputStream fos = new FileOutputStream("File_Name");既存のファイルを上書きします。だから最初のアプローチに行きます。
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をキャッチします。
プロジェクト内の任意の場所に関数を作成し、必要なときにその関数を呼び出すだけです。
皆さんは、非同期で呼び出していないアクティブスレッドを呼び出していることを覚えておく必要があります。正しく実行するには、5〜10ページで十分です。あなたのプロジェクトにより多くの時間を費やして、すでに書かれたものを書くことを忘れてはどうですか?正しく
    //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********/3行目は実際にテキストを追加するため、2行目のコードは2行です。:P
図書館
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
}Apache Commonsプロジェクトを提案するかもしれません。このプロジェクトはすでに、必要なことを行うためのフレームワークを提供しています(つまり、コレクションの柔軟なフィルタリング)。
次の方法では、ファイルにテキストを追加します。
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()次のコードを使用して、ファイルのコンテンツを追加できます。
 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);
    }*/
}