2

I have list of strings. I am trying to append those string values to a text file.

Here is my code:

java_location = "#{second}#{first}"

The output of java_location is:

1.6.0_43/opt/oracle/agent12c/core/12.1.0.4.0/jdk/bin/java
1.6.0_43/opt/oracle/agent12c/core/12.1.0.4.0/jdk/jre/bin/java
1.5.0/opt/itm/v6.2.2/JRE/lx8266/bin/java
1.6.0_35/u01/app/oracle/product/Middleware/Oracle_BI1/jdk/jre/bin/java

I want this output writing into a text file. How can i do that?

Mike Lyons
  • 1,748
  • 2
  • 20
  • 33
suppala
  • 35
  • 6
  • Have you read about how to write to a text file? What have you tried? The above does not seem to be code aside from the first line ... Here's a tutorial on writing to a file: http://rubylearning.com/satishtalim/read_write_files.html – Mike Lyons Dec 17 '14 at 17:29
  • But it is adding only one line.i.e 1.6.0_43/opt/oracle/agent12c/core/12.1.0.4.0/jdk/bin/java. It is not adding remaining lines to a text file – suppala Dec 17 '14 at 17:32
  • Loop over the lines, put them into a list and iterate over that, adding each line to the file. – Mike Lyons Dec 17 '14 at 17:36
  • Hi, tried to loop it. if first && second java_location = "#{second}#{first}" a << java_location File.open("/home/weblogic/javafoundmodified.txt", 'w+') do |file| a.each { |item| file.puts item } end end – suppala Dec 17 '14 at 19:15
  • 2
    Do not put code in a comment. Append it to your question and format it as code so it's readable. `File.open("/home/weblogic/javafoundmodified.txt", 'w+')`: Please read the [IO documentation](http://www.ruby-doc.org/core-2.1.5/IO.html#method-c-new) regarding use of the file mode flags, in particular look at `'a'`. – the Tin Man Dec 17 '14 at 19:56

2 Answers2

1
File.write('file.txt', java_location)
Adrian
  • 14,931
  • 9
  • 45
  • 70
0

You want to open the file in append mode ('a') rather than readwrite ('w+') which truncates the existing file to zero length before writing

http://alvinalexander.com/blog/post/ruby/example-how-append-text-to-file-ruby

if first && second 
  java_location = "#{second}#{first}" 
  a << java_location 
  File.open("/home/weblogic/javafoundmodified.txt", 'a') do |file| 
    a.each { 
    |item| 
    file.puts item 
    } 
  end 
end
Kyle
  • 156
  • 7