Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...