如何在文本文件中添加字符串 java

 

String htmlName="index.html";
String relaPath=""
		Writer out = null;
		String path = ServletActionContext.getServletContext().getRealPath("/");
		File fileName = new File(path + relaPath+"index.html");
		try {
			out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(fileName, true), "utf-8"));
			out.write("追加的东西");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

 

 

 

Java代码



1.
可以先把文件里面的东西读出来,放在StringBuffer里面,然后在追加   

    如:

    File f=new File; 
    try  
    {   
    InputStream a = new FileInputStream(f);   
    BufferedReader ins = new BufferedReader(new InputStreamReader(a)); 
    StringBuffer buffer = new StringBuffer();   
    String line = "";   
    while ((line = ins.readLine()) != null)   
    {   
    buffer.append(line);   
    System.out.println(buffer.toString());   
    }   
    buffer.append("后面的");   
    FileOutputStream out = new FileOutputStream(f);   
    out.write(buffer.toString().getBytes());   
    }   
    catch(Exception e)   
    {   
    e.printStackTrace();   
    }   




2.

Java代码 
File f=new File("D:/a.txt");
try
{
FileOutputStream out = new FileOutputStream(f,true);
out.write("something".getBytes());
}
catch(Exception e)
{
e.printStackTrace();
}




3.
FileOutputStream接收两个参数,后面个boolean决定是追加还是覆盖


Java代码

PrintWriter out = new PrintWriter(new BufferedWriter(   

                        new FileWriter(rcFile, true)), true);   

    out.println(sb.toString());  


 



    第一个true代表append,第二个代表autoflush  


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值