Java。如何將文本追加到file.txt的頂部
在開始寫入之前,可以使用RandomAccessFile來使用方法來 光標(biāo)并將其0th定位seek(long position)。
如本主題所述
RandomAccessFile f = new RandomAccessFile(new File('yourFile.txt'), 'rw');f.seek(0); // to the beginningf.write('Jennifer'.getBytes());f.close();
正如下面許多評(píng)論所指出的,此解決方案從一開始就 覆蓋 了文件內(nèi)容。要完全替換內(nèi)容,可能必須 刪除 并 重寫 File 。
解決方法我需要通過Java將文本添加到文本文件的開頭。
例如我有帶有數(shù)據(jù)的test.txt文件:
PeterJohnAlice
我需要添加(到文件頂部):
Jennifer
它應(yīng)該是:
JenniferPeterJohnAlice
我有一部分代碼,但是將數(shù)據(jù)追加到文件末尾,我需要將其添加到文件頂部:
public static void irasymas(String irasymai){try { File file = new File('src/lt/test.txt');if (!file.exists()) {file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile(),true); BufferedWriter bw = new BufferedWriter(fw); bw.write(irasymai+ 'rn'); bw.close();}catch (IOException e) {e.printStackTrace();} }
我已經(jīng)嘗試過了,但這只會(huì)從文件中刪除所有數(shù)據(jù),而不會(huì)插入任何文本:
public static void main(String[] args) throws IOException {BufferedReader reader = null;BufferedWriter writer = null;ArrayList list = new ArrayList();try { reader = new BufferedReader(new FileReader('src/lt/test.txt')); String tmp; while ((tmp = reader.readLine()) != null)list.add(tmp); OUtil.closeReader(reader); list.add(0,'Start Text'); list.add('End Text'); writer = new BufferedWriter(new FileWriter('src/lt/test.txt')); for (int i = 0; i < list.size(); i++)writer.write(list.get(i) + 'rn');} catch (Exception e) { e.printStackTrace();} finally { OUtil.closeReader(reader); OUtil.closeWriter(writer);} }
謝謝你的幫助。
相關(guān)文章:
1. 在應(yīng)用配置文件 app.php 中找不到’route_check_cache’配置項(xiàng)2. html按鍵開關(guān)如何提交我想需要的值到數(shù)據(jù)庫3. HTML 5輸入框只能輸入漢字、字母、數(shù)字、標(biāo)點(diǎn)符號(hào)?正則如何寫?4. javascript - 請(qǐng)教如何獲取百度貼吧新增的兩個(gè)加密參數(shù)5. gvim - 誰有vim里CSS的Indent文件, 能縮進(jìn)@media里面的6. 跟著課件一模一樣的操作使用tp6,出現(xiàn)了錯(cuò)誤7. PHP類屬性聲明?8. javascript - JS請(qǐng)求報(bào)錯(cuò):Unexpected token T in JSON at position 09. objective-c - ios 怎么實(shí)現(xiàn)微信聯(lián)系列表 最好是swift10. java - 安卓接入微信登錄,onCreate不會(huì)執(zhí)行
