如何在java中向现有文件追加文本?

oiopk7p5  于 2021-07-04  发布在  Java
关注(0)|答案(31)|浏览(577)

我需要在java中重复地向现有文件追加文本。我该怎么做?

kcwpcxri

kcwpcxri1#

您可以使用以下代码将内容附加到文件中:

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

iyr7buue2#

使用java.nio.files和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 . PrintWriterprintln() 方法,然后可以调用以写入文件。
这个 StandardOpenOption 此代码中使用的参数:打开文件进行写入,仅附加到文件,如果文件不存在,则创建该文件。 Paths.get("path here") 可以替换为 new File("path here").toPath() . 以及 Charset.forName("charset name") 可以修改以适应所需的 Charset .

bf1o4zei

bf1o4zei3#

我只是补充了一些小细节:

new FileWriter("outfilename", true)

2.nd参数(true)是一个称为appendable的特性(或接口)(http://docs.oracle.com/javase/7/docs/api/java/lang/appendable.html). 它负责向特定文件/流的末尾添加一些内容。这个接口是从Java1.5开始实现的。具有此接口的每个对象(即bufferedwriter、CharraryWriter、charbuffer、filewriter、filterwriter、logstream、outputstreamwriter、pipedwriter、printstream、printwriter、stringbuffer、stringbuilder、stringwriter、writer)都可用于添加内容
换句话说,您可以向gzip文件或http进程添加一些内容

enyaitl3

enyaitl34#

在java-7中,也可以这样做:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

//

2fjabf4q

2fjabf4q5#

/**********************************************************************
 * 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()
xytpbqjk

xytpbqjk6#

稍微扩展一下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) ).
这个 CREATE 选项仅在指定的目录已存在时才起作用-如果不存在,则 NoSuchFileException 被抛出。如果需要,可以在设置后添加以下代码 path 要创建目录结构,请执行以下操作:

Path pathParent = path.getParent();
if (!Files.exists(pathParent)) {
    Files.createDirectories(pathParent);
}
clj7thdc

clj7thdc7#

您也可以尝试以下方法:

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
}
az31mfrm

az31mfrm8#

如果您想在特定行中添加一些文本,您可以首先读取整个文件,在任何地方添加文本,然后覆盖以下代码中的所有内容:

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();
    }
}
r1wp621o

r1wp621o9#

此代码将满足您的需要:

FileWriter fw=new FileWriter("C:\\file.json",true);
   fw.write("ssssss");
   fw.close();
jei2mxaa

jei2mxaa10#

如果我们使用的是java7及更高版本,并且还知道要添加(附加)到文件中的内容,那么我们可以使用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没有要求,但只是为了以防万一,我们想搜索一些特定的关键字行,例如。 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();
}
dz6r00yl

dz6r00yl11#

我的回答是:

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
}
6kkfgxo0

6kkfgxo012#

在项目中的任何地方创建一个函数,并在需要时调用该函数。
伙计们,你们要记住,你们在调用活动线程,而不是异步调用,因为这可能是一个很好的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

pkln4tw6

pkln4tw613#

这里的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();
    }
}

另外,从Java7开始,您可以使用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);
}
yrdbyhpb

yrdbyhpb14#

图书馆

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);
    }
}
7d7tgy0s

7d7tgy0s15#

Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
    Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);

相关问题