If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Friday, March 28, 2014

Ceylon: dealing with files

As we saw earlier Ceylon is modularized. So the API to deal with files is not part of the core language. Check Modularity for how to specify a dependency on Ceylon file.
import ceylon.file { ... }
/**
the parsePath function returns a Path. A path's resource either refers to an ExistingResource or Nil.
An ExistingResource is one of File|Directory|Link.
**/
void readFile() {
Path demoFilePath = parsePath("c:/tmp/demo.txt");
if (is File file = demoFilePath.resource) {
//below we define a resource expression. We don't need to take care of opening and
//closing the resource ourselves.
try (reader = file.Reader()) {
//readLine returns a String?, null if there is no more line so we
//conveniently print lines while the end of file has not been reached
while (is String line = reader.readLine()) {
print(line);
}
}
}
}
import ceylon.file { ... }
/**
In this little exercise we will write all words from a text to
a newline starting with a line number to a file:
0:I
1:like
2:programming
**/
void writeFile() {
String text = "I like programming";
Path filePath = parsePath("c:/tmp/words.txt");
//now we need to make sure the file does not already exist
if (is Nil resource = filePath.resource) {
File file = resource.createFile();
try (writer = file.Overwriter()) {
for (index -> word in entries(text.split())) {
writer.writeLine("``index``:``word``");
}
}
}
}
/**
Let's say we want to move the following folder
c:/tmp/map1 and its content
to
c:/tmp/movedmap
**/
void moveFolder() {
Path sourcePath = parsePath("c:/tmp/map1");
Path targetPath = sourcePath.siblingPath("movedmap");
if (is Directory sourceDir = sourcePath.resource) {
if (is Nil targetDir = targetPath.resource) {
sourceDir.move(targetDir);
}
}
}

No comments:

Post a Comment