将字符串复制到Java中文件的开头 [英] Copy a string to the beginning of a file in Java

查看:150
本文介绍了将字符串复制到Java中文件的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在文件的开头写入一个字符串,我该怎么做?

I want to write a string into the beginning of a file, How do I do that?

我根本不知道如何添加字符串.这是我到目前为止所做的:

I don't know how to add a string at all.. This is what I did so far:

  public static void prepend (String filename, String data) throws IOException{

    FileOutputStream file= new FileOutputStream(filename);

}

(i)write()方法仅接受字节-我该怎么做才能在我的情况下使用它?

(i) The write() method accepts only bytes- What should I do in order to use it in my case?

(ii)-如何将字符串复制到文件的开头?

(ii)-How do I copy the string to the beginning of the file?

而且-如果有人知道一个网站,该网站具有所有作家\读者以及所有这些流的排列方式并得到了很好的解释-我将不胜感激,我会迷失方向.

And- If someone knows about a web-site that has all the Writers\Readers and all these streams arranged and well explained- I will really appreciate it, I'm losing my mind.

谢谢!

推荐答案

要编写 text ,您需要创建一个Writer-例如OutputStreamWriter.您可以 代替使用FileWriter,但是我更喜欢将FileOutputStream包裹在OutputStreamWriter中,这样我就可以控制编码了.

To write text, you need to create a Writer - such as OutputStreamWriter. You can use FileWriter instead, but I prefer to wrap a FileOutputStream in an OutputStreamWriter as that way I can control the encoding.

虽然您不能真正地放在文件的开头-您必须将新文本写入新文件的开头,然后再复制旧文件的内容,然后在必要时重命名文件.确切的操作方式将取决于现有文件的内容.

You can't really prepend to the start of a file though - you'll have to write the new text to the start of a new file, then copy the contents of the old file afterwards, then rename the files if necessary. Exactly how you do that will depend on the contents of the existing file.

这篇关于将字符串复制到Java中文件的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆