Skip to main navigation Skip to main content Skip to page footer

Copying Files to Android

The Android filesystems do not accept arbitrary characters in file names, I learned the hard way. I used the Dolphin file manager to copy files to Android via USB. The copying process stalled ever and ever again, without any helpful message.

At first I switched on developer mode, changed the settings to keep the screen on while charging and to enable USB debugging. After many unsuccessful trials, I finally realized that some file names contained illegal characters. Normally, I use strict discipline and name files only with a very restricted character set, but alas, the files I wanted to copy had their names generated by music management software. 

The coolest way would be to patch the file manager to rename files on the fly, but that would mean more effort than I was able to afford. So I wrote a Perl script, and here it is:

#!/usr/bin/perl -w
use strict;

my $reservedchars = "|\\?*<\":>+[]()/'";

my %ersetzer = ();

sub setupErsetzer
{
    my  @chars = split //, $reservedchars;
    foreach my $mychar (@chars) {
	$ersetzer{$mychar} = sprintf("%%%x", ord($mychar));
    }
}

sub sanitizeFilename
{
    my $dir = shift;
    my $fn = shift;
    my ($neu, $mychar, $abwo);
    my $changed = 0;
    $neu = $fn;
    foreach $mychar (keys %ersetzer) {
	$abwo = 0;
	while (($abwo = index($neu, $mychar, $abwo)) > -1) {
	    $changed++;
	    $neu = substr($neu, 0, $abwo) . $ersetzer{$mychar} .
		substr($neu, $abwo + 1);
	}
    }
    if ($changed > 0) {
	print "Renaming $dir$fn\n     to  $dir$neu\n";
    }
    rename "$dir$fn", "$dir$neu";
}

sub parseDirectory
{
    my $dir = shift;
    my ($dh, $filename, $longname);
    opendir $dh, $dir or die;
    print "Entering Dir $dir\n";
    while ($filename = readdir $dh) {
	next if ($filename eq '.' or $filename eq '..');
	if (substr($dir, -1) ne '/') {
	    $dir .= '/';
	}
	$longname = $dir . $filename;
	if (-d $longname) {
	    # hope it works
	    parseDirectory ($longname);
	    sanitizeFilename ($dir, $filename);
	} elsif (-f $longname) {
	    sanitizeFilename ($dir, $filename);
	} else {
	    next;
	}
    }
}

my $folder = shift || '.';

setupErsetzer;

parseDirectory $folder;