我需要反复文本追加到Java中的现有文件。我怎么做?
你可以进行日志记录这样做呢?如果是这样有several libraries for this。最流行的两个是Log4j和Logback。
如果你只是需要做到这一次,Files class让一切变得简单:
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
如果文件不存在。它也不会追加自动换行(追加到文本文件时,你经常需要)。 Steve Chambers's answer涵盖了你可以如何与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
}
}
与java.nio.file.Files一起使用java.nio.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的,作家)与该接口可用于添加内容
换句话说,你可以添加一些内容到您的gzip压缩的文件,或者一些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();
}
这会做你想要什么..
最好使用尝试 - 与资源那么所有预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没有要求,但为了以防万一,我们要寻找有一些特定的关键字如线confidential
我们可以利用流的API在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
您可以使用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());
}
图书馆
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");
这将覆盖现有文件。所以要为第一种方法。
我可能会建议apache commons project。该项目已经提供了一个框架,做什么,你需要(集合即灵活的过滤)。
下面的方法让我们您文本追加到一些文件:
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();
应该不是所有的答案在这里用try / catch块的有.close包含在finally块()块?
例如,对于明显的答案:
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 statement。没有最后需要块关闭,因为它是自动处理的,也是那么详细的申报资源(S):
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
out.println("the text");
} catch (IOException e) {
System.err.println(e);
}
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);
}*/
}
编辑 - 例如Apache下议院2.1,做正确的做法是:
FileUtils.writeStringToFile(file, "String to append", true);
我适应@基普的解决方案,以妥善包括关闭在最后的文件:
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's answer略有扩大,这里是一个简单的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)
)。
这是一个有点令人震惊的有多少,这些答案的保留文件处理发生错误的情况下打开。答案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.
}
在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到现有文件。利用这一点,从增加不必要的库到类路径中为您节省。
这可以通过一行代码来完成。希望这可以帮助 :)
Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);