سؤال

أحتاج إلى إلحاق النص بشكل متكرر بملف موجود في Java.كيف يمكنني فعل ذلك؟

هل كانت مفيدة؟

المحلول

هل تفعل هذا لأغراض التسجيل؟إذا كان الأمر كذلك هناك عدة مكتبات لهذا الغرض.اثنان من الأكثر شعبية هي Log4j و تسجيل الدخول مرة أخرى.

جافا 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
}

حذر:النهج أعلاه سوف يرمي NoSuchFileException إذا كان الملف غير موجود بالفعل.كما أنه لا يقوم بإلحاق سطر جديد تلقائيًا (وهو ما تريده غالبًا عند إلحاقه بملف نصي). إجابة ستيف تشامبرز يغطي كيف يمكنك القيام بذلك مع 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
    }
}

نصائح أخرى

ويمكنك استخدام 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());
}

وإذا لم يكن كل من الإجابات هنا مع كتل حاول / 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();
    }
} 

وأيضا، كما في جافا 7، يمكنك استخدام try- مع الموارد بيان . لا أخيرا مطلوب كتلة لإغلاق الموارد المعلنة (ق) ليتم التعامل معه تلقائيا، وأيضا أقل مطول:

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
}

تعديل - يمكنك حتى أباتشي العموم 2.1، والطريقة الصحيحة للقيام بذلك هي:

FileUtils.writeStringToFile(file, "String to append", true);

<الصورة> I تكييفها @ حل كيب لتشمل بشكل صحيح إغلاق الملف على النهاية:

<الصورة>
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();
        }
    }
}

<الصورة>

لتوسيع قليلا على كيب في الإجابة ، هنا هو بسيط جافا 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)، بديلا <لأ href = "https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html #write (java.nio.file.Path،٪ 20byte []،٪ 20java.nio.file.OpenOption ...) "يختلط =" noreferrer "> الزائد 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
     }
  }

تحرير:

واعتبارا من جافا 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.
  }

في جافا 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);

جافا 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. 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)

المعلمة الثانية (صحيح) هي ميزة (أو واجهة) تسمى قابل للإلحاق (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) مع هذه الواجهة يمكن استخدامها لإضافة محتوى

بمعنى آخر، يمكنك إضافة بعض المحتوى إلى ملفك المضغوط، أو بعض عمليات 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.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();         
    }

وهذا سوف تفعل ما كنت تنوي ل..

وأفضل استخدام محاولة مع الموارد ثم كل ما قبل جافا 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 وما فوق ونعرف أيضًا المحتوى المراد إضافته (إلحاقه) بالملف فيمكننا الاستفادة منه newBufferedWriter الطريقة في حزمة 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();
    }
}

هناك بعض النقاط التي يجب ملاحظتها:

  1. من العادة الجيدة دائمًا تحديد ترميز مجموعة الأحرف ولهذا لدينا ثابت في الفصل StandardCharsets.
  2. يستخدم الكود try-with-resource عبارة يتم فيها إغلاق الموارد تلقائيًا بعد المحاولة.

على الرغم من أن OP لم يطلب ذلك ولكن فقط في حالة أردنا البحث عن أسطر تحتوي على بعض الكلمات الرئيسية المحددة على سبيل المثال. confidential يمكننا الاستفادة من واجهات برمجة التطبيقات المتدفقة في Java:

//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 مكان المنبع.

وإنشاء وظيفة في أي مكان في المشروع، وندعو ببساطة أن وظيفة أي وقت مضى حيث كنت في حاجة إليها.

والرجال عليك أن تذكر أنك الرجال يدعون المواضيع النشطة التي كنت لا ندعو بشكل غير متزامن ونظرا لأنه من المرجح أن تكون جيدة 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********/

وثلاثة خطوط من التعليمات البرمجية اثنين حقا منذ الثالث بإلحاق النص في الواقع. : 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
}
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);

والحقيقية يسمح لإلحاق البيانات في ملف موجود. إذا سوف نكتب

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()

ويمكنك استخدام التعليمات البرمجية التالية إلى إلحاق محتوى في الملف:

 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);
    }*/
}
scroll top