During our development of the android program, we often need to check how the android source code is implemented. At this time, we need to add the android source code to eclipse. After we obtain the android source code through git and repo, We need to extract the Java file, and put it under the source subdirectory of the android SDK. It takes a lot of time to manually extract these java files, so we can write a Python script to automatically extract the java files in the android source code, as shown below:
From _ future _ import with_statement # For python <2.6
Import OS
Import re
Import zipfile
# Open a zip file
Dst_file = 'sources.zip'
If OS. Path. exists (dst_file ):
Print dst_file, "already exists"
Exit (1)
Zip = zipfile. zipfile (dst_file, 'w', zipfile. zip_deflated)
# Some files are duplicated, copy them only once
Written = {}
# Iterate over all java files
For Dir, subdirs, files in OS. Walk ('.'):
For file in files:
If file. endswith ('. Java '):
# Search package name
Path = OS. Path. Join (Dir, file)
With open (PATH) as F:
For line in F:
Match = Re. Match (R'/S * package/S + ([a-zA-Z0-9/. _] +); ', line)
If match:
# Copy source into the ZIP file using the package as path
Zippath = match. Group (1). Replace ('.', '/') + '/' + File
If zippath not in written:
Written [zippath] = 1
Zip. Write (path, zippath)
Break;
Zip. Close ()