RingJavafor Ring

Files and folders

Read and write text files, append, list a folder, copy, move and delete with java.nio.file.

What you will learn#

The program#

samples/UsingJava/tutorials/ch06_files.ring
# Tutorial 6: files and folders - java.nio.file
load "java.ring"

using {
	"java.io"
	"java.nio.file"
	"java.nio.charset"
}

Files = new Files
StandardOpenOption = new StandardOpenOption

oFolder = Files.createTempDirectory(["tutorial",[]])
oFile = oFolder.resolve("notes.txt")
? "the file name: " + oFile.getFileName().toString()

# writing and reading a whole text (UTF-8)
Files.writeString([oFile,"first line" + nl + "second line" + nl + "third: مرحبا",[]])
? Files.size(oFile)
? Files.readString(oFile)
aLines = Files.readAllLines(oFile).toList()
for cLine in aLines
	? "> " + cLine
next

# appending: the options are Java enum values
oOptions = [ StandardOpenOption.APPEND ]
Files.writeString([oFile,nl + "fourth line",oOptions])
? len(Files.readAllLines(oFile).toList())

# a folder with a few files
Files.writeString([oFolder.resolve("a.txt"),"A",[]])
Files.writeString([oFolder.resolve("b.log"),"B",[]])
Files.createDirectory(oFolder.resolve("sub"),[])
oStream = Files.list(oFolder)
aNames = []
aItems = oStream.toList()
for oItem in aItems
	aNames + oItem.getFileName().toString()
next
oStream.close()
aNames = sort(aNames)
for cName in aNames
	? "  " + cName
next

# copying, moving, deleting
Files.copy([oFile,oFolder.resolve("copy.txt"),[]])
? Files.exists(oFolder.resolve("copy.txt"),[])
Files.delete(oFolder.resolve("copy.txt"))
? Files.exists(oFolder.resolve("copy.txt"),[])

# the old classes still work: PrintWriter and BufferedReader
oWriter = new PrintWriter(new FileWriter(oFolder.resolve("old.txt").toString()))
oWriter.@println("written with a PrintWriter")
oWriter.close()
oReader = new BufferedReader(new FileReader(oFolder.resolve("old.txt").toString()))
? oReader.readLine()
oReader.close()

# clean up: delete the files, then the folder
aItemList = Files.list(oFolder).toList()
for oItem in aItemList
	Files.delete(oItem)
next
Files.delete(oFolder)
? Files.exists(oFolder,[])
Output
the file name: notes.txt
40
first line
second line
third: مرحبا
> first line
> second line
> third: مرحبا
4
  a.txt
  b.log
  notes.txt
  sub
1
0
written with a PrintWriter
0

How it works#

A Path names a file; Files has the methods that work on it. The options of a Java method (StandardOpenOption.APPEND) are enum values, and a Java array is made with jArray("type", items). The program deletes everything it made at the end.

Exercises#

  1. Count the lines of a text file.
  2. Copy a file to a new name and compare their sizes.
  3. List the files of a folder, biggest first.

Next#

When things go wrong

RingJava - use Java classes and methods from Ring programs.