read

How to access Map values in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is one of the shortest recipes, Recipe 11.17, “How to Access Map Values in Scala”

Problem

You want to access individual values stored in a map. You may have tried this and run into an exception when a key didn’t exist, and want to see how to avoid that exception.

Solution

Given a sample map:

Android: How to load an image from a file and set on an ImageView

If you’re working with an Android application, this source code seems to work to load an image from a file:

Bitmap bitmap = BitmapFactory.decodeFile(pathToPicture);

The Bitmap and BitmapFactory classes are located in the android.graphics package:

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

Assuming that your pathToPicture is correct, you can then add this bitmap image to an ImageView like this:

How to read a file URL in Java and Scala

I thought this might be harder, but if you have a file URL like “file:///Users/al/SherlockHolmes.txt”, and want to read those file contents as a Java URL, the process in Java and Scala is simple, as shown in this Scala code:

A Bash ‘for’ loop to iterate over a file that has blank spaces in its lines

I just had to write a Linux bash shell script that has a for loop that reads a file, and that file contains lines with blank spaces in it. This sounds simple, but blank spaces cause major problems in a Bash for loop.

Fortunately there’s a simple solution: Before the for loop, declare the input field separator to be a newline character, as shown in this for loop code:

How to read and write from a file in a Linux bash shell script

I’m currently writing a complicated Linux bash shell script where I need to keep a counter in an external file, and to do so, I need to be able to write to a file and then read from that file.

In short, this is how I write my counter to that file:

# create a variable to represent the filename
COUNTER_FILE="counter.tmp"

# write to the file
echo "0" > $COUNTER_FILE

Later in the code I increment the counter and write it to the file like this:

A collection of Scala XML tutorials alvin February 20, 2014 - 9:02pm

The following links are a collection of Scala XML tutorials I've written. Most of them come from the Scala Cookbook, while the others were written before I wrote the Cookbook.

Without any further ado, here are the links:

Scala file reading performance: Line counting algorithms

Out of curiosity about Scala’s file-reading performance, I decided to write a “line count” program in Scala. One obvious approach was to count the newline characters in the file: