JAVA如何在文件头添加内容?

JAVA如何在文件头添加内容?,第1张

“先读入,再写回”的方法时可行的

这个文件有几十兆,不代表整个读入,不是占用几十兆内存。先写入头部的文字,再循环读一点源文件,写一点源文件。

RandomAccessFile 也可以,只是最初要留出空间,比如一些空格

//往文件头加数据

@Test

public void test6() throws Exception{

File f=new File("c:/lowertest.txt")

RandomAccessFile r=new RandomAccessFile(f, "rw")

r.seek(0)

r.write("www".getBytes())

r.close()

}

  向txt文件写入内容基本思路就是获得一个file对象,新建一个txt文件,打开I/O *** 作流,使用写入方法进行读写内容,示例如下:

package common

import java.io.*

import java.util.ArrayList

public class IOTest {

public static void main (String args[]) {

ReadDate()

WriteDate()

}

/**

* 读取数据

*/

public static void ReadDate() {

String url = “e:/2.txt”

try {

FileReader read = new FileReader(new File(url))

StringBuffer sb = new StringBuffer()

char ch[] = new char[1024]

int d = read.read(ch)

while(d!=-1){

String str = new String(ch,0,d)

sb.append(str)

d = read.read(ch)

}

System.out.print(sb.toString())

} catch (FileNotFoundException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

}

}

/**

* 写入数据

*/

public static void WriteDate() {

try{

File file = new File(“D:/abc.txt”)

if (file.exists()) {

file.delete()

}

file.createNewFile()

BufferedWriter output = new BufferedWriter(new FileWriter(file))

ArrayList ResolveList = new ArrayList()

for (int i = 0 i < 10 i++) {

ResolveList.add(Math.random()* 100)

}

for (int i=0 i 

output.write(String.valueOf(ResolveList.get(i)) + “\n”)

}

output.close()

} catch (Exception ex) {

System.out.println(ex)

}

}

}

原文出自【比特网】,转载请保留原文链接:http://soft.chinabyte.com/database/303/12439303.shtml


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11822177.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-18
下一篇2023-05-18

发表评论

登录后才能评论

评论列表(0条)

    保存