Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

java - How to prepend to a file (add at the top)

Imagine you have a file

sink("example.txt")
data.frame(a = runif(10), b = runif(10), c = runif(10))
sink()

and would want to add some header information, like

/* created on 31.3.2011 */
/* author */
/* other redundant information */

How would I add this "header"? Doing it manually seems trivial. Hit a few Enters, copy/paste or write information and you're done. Of course, in R, I could read in example.txt, create example2.txt, add header information and then example.txt.

I was wondering if there's another way of appending files from the "top". Other solutions (from c++ or Java...) also welcome (I'm curious how other languages approach this problem).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

in R there is no need to work with an extra file. You can just do :

writeLines(c(header,readLines(File)),File)

Yet, using the linux shell seems the most optimal solution, as R is not famous for performant file reading and writing. Especially not since you have to read in the complete file first.

Example :

Lines <- c(
"First line",
"Second line",
"Third line")
File <- "test.txt"
header <- "A line 
Another line 
More line 

"

writeLines(Lines,File)
readLines(File)    

writeLines(c(header,readLines(File)),File)
readLines(File)
unlink(File)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...