This post demonstrates how to read and write text files in several scenarios. It makes some short references to equivalent Java concepts and codes.
Ruby, Java, and Others
Here is some information about the environment used for this Ruby post.
- Windows 10
- Windows command line
- Notepad++
- Ruby for Windows
- ruby 2.3.1p112 (2016-04-26 revision 54768) [x64-mingw32]
- http://ruby-doc.org/core-2.3.1/
- Java 8 – JDK
- Eclipse Mars
Reading and Writing Files
Reading and writing files in Ruby require the use of the Class IO which is part of Ruby’s Core API. Think of it like the Java IO package.
Read and Write in Bulk
In Ruby
1 2 3 4 5 6 7 8 | # Read the whole content of file in_data.txt text_data = IO.read("in_data.txt") # Display the read text data print text_data # Write the text data to out_data.txt IO.write("out_data.txt", text_data) |
In Java
The equivalent Java codes are as follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; public class MyClass { public static void main(String[] args) throws IOException { String contents = new String(Files.readAllBytes(Paths.get("C:\\SOMEWHERE\\in_data.txt"))); System.out.println(contents); try( PrintWriter out = new PrintWriter( "C:\\SOMEWHERE\\out_data.txt" ) ){ out.println( contents ); } } } |
Read and Write line by line
In Ruby
1 2 3 4 5 | file = File.open("out_data.txt", "w") IO.foreach("in_data.txt") { |text_data| print text_data file.write(text_data) } |
In Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; public class MyClass { public static void main(String[] args) throws IOException { InputStream is = new FileInputStream("C:\\SOMEWHERE\\in_data.txt"); BufferedReader buf = new BufferedReader(new InputStreamReader(is)); File fout = new File("C:\\SOMEWHERE\\out_data.txt"); FileOutputStream fos = new FileOutputStream(fohttps://turreta.com/blog/wp-admin/post.php?post=1661&action=edit#ut); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); String line = null; while ((line = buf.readLine()) != null) { bw.write(line); bw.newLine(); } buf.close(); bw.close(); } } |