简体   繁体   English

写入文本文件而不用Java覆盖

[英]Write to text file without overwriting in Java

I am trying to write a method that makes a "log.txt file" if one does not already exist and then writes to the file.我正在尝试编写一种方法,如果一个“log.txt 文件”尚不存在,然后写入该文件。 The problem that I am encountering is every time I call the method, it overwrites the existing log.我遇到的问题是每次调用该方法时,它都会覆盖现有日志。 How do I change the method so that instead of overwriting the data it just updates the file?如何更改方法,以便不覆盖数据而是只更新文件?

My Write File Method:我的写文件方法:

    File log = new File("log.txt")
    try{
    if(log.exists()==false){
            System.out.println("We had to make a new file.");
            log.createNewFile();
    }
    PrintWriter out = new PrintWriter(log);
    out.append("******* " + timeStamp.toString() +"******* " + "\n");
    out.close();
    }catch(IOException e){
        System.out.println("COULD NOT LOG!!");
    }

Just change PrintWriter out = new PrintWriter(log);只需更改PrintWriter out = new PrintWriter(log); to

PrintWriter out = new PrintWriter(new FileWriter(log, true));

use a FileWriter instead.改用 FileWriter。

FileWriter(File file, boolean append)

the second argument in the constructor tells the FileWriter to append any given input to the file rather than overwriting it.构造函数中的第二个参数告诉 FileWriter 将任何给定的输入附加到文件中,而不是覆盖它。

here is some code for your example:这是您的示例的一些代码:

File log = new File("log.txt")

try{
    if(!log.exists()){
        System.out.println("We had to make a new file.");
        log.createNewFile();
    }

    FileWriter fileWriter = new FileWriter(log, true);

    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write("******* " + timeStamp.toString() +"******* " + "\n");
    bufferedWriter.close();

    System.out.println("Done");
} catch(IOException e) {
    System.out.println("COULD NOT LOG!!");
}

For some reason, none of the other methods worked for me...So i tried this and worked.出于某种原因,其他方法都不适合我......所以我尝试了这个并且工作了。 Hope it helps..希望能帮助到你..

JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file\n hi \n hello \n hola";
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) {
    System.out.println(e);
}
JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "put here the data to be wriiten";
try
    {
    FileWriter fw = new FileWriter(write_file);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(Content);
    bw.append("hiiiii");
    bw.close();
    fw.close();
    }
catch(Exception e)
   {
    System.out.println(e);
   `}

You can even use FileOutputStream to get what you need.您甚至可以使用FileOutputStream来获取所需内容。 This is how it can be done,这是可以做到的,

File file = new File(Environment.getExternalStorageDirectory(), "abc.txt");
FileOutputStream fOut = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("whatever you need to write");
osw.flush();
osw.close();

您可以更改 PrintWriter 并使用 getAbsoluteFile() 方法,此函数返回给定抽象路径名的绝对 File 对象。

PrintWriter out = new PrintWriter(new FileWriter(log.getAbsoluteFile(), true));

try this one试试这个

 public void writeFile(String arg1,String arg2) { try { if (!dir.exists()) { if (dir.mkdirs()) { Toast.makeText(getBaseContext(), "Directory created", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getBaseContext(), "Error writng file " + filename, Toast.LENGTH_LONG) .show(); } } else { File file = new File(dir, filename); if (!file.exists()) { file.createNewFile(); } FileWriter fileWritter = new FileWriter(file, true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); bufferWritter.write(arg1 + "\\n"); bufferWritter.close(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(getBaseContext(), "Error writng file " + e.toString(), Toast.LENGTH_LONG) .show(); } }

Here is a simple example of how it works, best practice to put a try\\catch into it but for basic use this should do the trick.这是一个简单的例子,它是如何工作的,最好的做法是将 try\\catch 放入其中,但对于基本使用,这应该可以解决问题。 For this you have a string and file path and apply thus to the FileWriter and the BufferedWriter.为此,您有一个字符串和文件路径,并因此应用于 FileWriter 和 BufferedWriter。 This will write "Hello World"(Data variable) and then make a new line.这将写入“Hello World”(数据变量),然后换行。 each time this is run it will add the Data variable to the next line.每次运行时,它都会将 Data 变量添加到下一行。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;


String Data = "Hello World";
File file = new File("C:/Users/stuff.txt");
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(Data);
bw.newLine();
bw.close();
BufferedWriter login = new BufferedWriter(new FileWriter("login.txt"));

如果您想在一行中创建一个文件,这是一个示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM