Android Tutorial - File : Stream
Playing Back Audio Streams
package app.test; import java.io.IOException; import android.app.Activity; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.widget.TextView; public class Test extends Activity { MediaPlayer mediaPlayer; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView textView = new TextView(this); setContentView(textView); setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayer = new MediaPlayer(); try { AssetManager assetManager = getAssets(); AssetFileDescriptor descriptor = assetManager.openFd("a.ogg"); mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength()); mediaPlayer.prepare(); mediaPlayer.setLooping(true); } catch (IOException e) { textView.setText(e.getMessage()); mediaPlayer = null; } } @Override protected void onResume() { super.onResume(); if (mediaPlayer != null) { mediaPlayer.start(); } } protected void onPause() { super.onPause(); if (mediaPlayer != null) { mediaPlayer.pause(); if (isFinishing()) { mediaPlayer.stop(); mediaPlayer.release(); } } }
}
Stream Proxy
//package com.mediaportal.ampdroid.activities.videoplayback; import android.util.Log; import org.apache.http.Header; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.ParseException; import org.apache.http.ProtocolVersion; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ClientConnectionOperator; import org.apache.http.conn.OperatedClientConnection; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.DefaultClientConnection; import org.apache.http.impl.conn.DefaultClientConnectionOperator; import org.apache.http.impl.conn.DefaultResponseParser; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.io.HttpMessageParser; import org.apache.http.io.SessionInputBuffer; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicLineParser; import org.apache.http.message.ParserCursor; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.CharArrayBuffer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.StringTokenizer; public class StreamProxy implements Runnable { private static final String LOG_TAG = StreamProxy.class.getName(); private int port = 0; public int getPort() { return port; } private boolean isRunning = true; private ServerSocket socket; private Thread thread; private String mUrl; public void init() { try { socket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[] {127,0,0,1})); socket.setSoTimeout(5000); port = socket.getLocalPort(); Log.d(LOG_TAG, "port " + port + " obtained"); } catch (UnknownHostException e) { Log.e(LOG_TAG, "Error initializing server", e); } catch (IOException e) { Log.e(LOG_TAG, "Error initializing server", e); } } public void start(String url) { mUrl = url; if (socket == null) { throw new IllegalStateException("Cannot start proxy; it has not been initialized."); } thread = new Thread(this); thread.start(); } public void stop() { isRunning = false; if (thread == null) { throw new IllegalStateException("Cannot stop proxy; it has not been started."); } thread.interrupt(); try { thread.join(5000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void run() { Log.d(LOG_TAG, "running"); while (isRunning) { try { Socket client = socket.accept(); if (client == null) { continue; } Log.d(LOG_TAG, "client connected"); HttpRequest request = readRequest(client); processRequest(request, client); } catch (SocketTimeoutException e) { // Do nothing } catch (IOException e) { Log.e(LOG_TAG, "Error connecting to client", e); } } Log.d(LOG_TAG, "Proxy interrupted. Shutting down."); } private HttpRequest readRequest(Socket client) { HttpRequest request = null; InputStream is; String firstLine; try { is = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192); firstLine = reader.readLine(); } catch (IOException e) { Log.e(LOG_TAG, "Error parsing request", e); return request; } if (firstLine == null) { Log.i(LOG_TAG, "Proxy client closed connection without a request."); return request; } StringTokenizer st = new StringTokenizer(firstLine); String method = st.nextToken(); //String uri = st.nextToken(); // Log.d(LOG_TAG, uri); // String realUri = uri.substring(1); // Log.d(LOG_TAG, realUri); request = new BasicHttpRequest(method, mUrl); return request; } private HttpResponse download(String url) { DefaultHttpClient seed = new DefaultHttpClient(); SchemeRegistry registry = new SchemeRegistry(); registry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SingleClientConnManager mgr = new SingleClientConnManager(seed.getParams(), registry); DefaultHttpClient http = new DefaultHttpClient(mgr, seed.getParams()); HttpGet method = new HttpGet(url); HttpResponse response = null; try { Log.d(LOG_TAG, "starting download"); response = http.execute(method); Log.d(LOG_TAG, "downloaded"); } catch (ClientProtocolException e) { Log.e(LOG_TAG, "Error downloading", e); } catch (IOException e) { Log.e(LOG_TAG, "Error downloading", e); } return response; } private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException { if (request == null) { return; } Log.d(LOG_TAG, "processing"); String url = request.getRequestLine().getUri(); HttpResponse realResponse = download(url); if (realResponse == null) { return; } Log.d(LOG_TAG, "downloading..."); InputStream data = realResponse.getEntity().getContent(); StatusLine line = realResponse.getStatusLine(); HttpResponse response = new BasicHttpResponse(line); response.setHeaders(realResponse.getAllHeaders()); Log.d(LOG_TAG, "reading headers"); StringBuilder httpString = new StringBuilder(); httpString.append(response.getStatusLine().toString()); httpString.append("\n"); for (Header h : response.getAllHeaders()) { httpString.append(h.getName()).append(": ").append(h.getValue()).append( "\n"); } httpString.append("\n"); Log.d(LOG_TAG, "headers done"); try { byte[] buffer = httpString.toString().getBytes(); int readBytes; Log.d(LOG_TAG, "writing to client"); client.getOutputStream().write(buffer, 0, buffer.length); // Start streaming content. byte[] buff = new byte[1024 * 50]; while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) { client.getOutputStream().write(buff, 0, readBytes); } } catch (Exception e) { Log.e("", e.getMessage(), e); } finally { if (data != null) { data.close(); } client.close(); } }
}
Copy Stream
import java.io.InputStream; import java.io.OutputStream; class Main { public static void CopyStream(InputStream is, OutputStream os) { final int buffer_size = 1024; try { byte[] bytes = new byte[buffer_size]; for (;;) { int count = is.read(bytes, 0, buffer_size); if (count == -1) break; os.write(bytes, 0, count); } } catch (Exception ex) { } }
}
Ini File Stream Reader
//package org.ametro.model.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class IniStreamReader { private static final int BUFFER = 8196; private final BufferedReader mStream; private String mSection; private String mKey; private String mValue; private boolean mSectionChanged; public IniStreamReader(InputStreamReader stream) throws IOException{ mStream = new BufferedReader(stream, BUFFER); mSection = null; mValue = null; mSectionChanged = false; } public String getSection(){ return mSection; } public String getKey(){ return mKey; } public String getValue(){ return mValue; } public boolean isSectionChanged(){ return mSectionChanged; } public boolean readNext() throws IOException{ String line = mStream.readLine(); boolean hasResult = false; mSectionChanged = false; while(line!=null){ line = line.trim(); if(line.length() != 0){ if(line.startsWith("[") && line.endsWith("]") ){ mSection = line.substring(1, line.length() - 1); mSectionChanged = true; }else if( line.indexOf('=')!=-1 && !(line.startsWith("#") || line.startsWith(";")) ) { String[] parts = line.split("="); mKey = parts[0].trim(); mValue = parts.length > 1 ? parts[1].trim() : ""; hasResult = true; break; } } line = mStream.readLine(); } return hasResult; } }
Read InputStream fully to a string
//package org.anddev.andengine.util; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.util.Scanner; /** class StreamUtils { public static final int IO_BUFFER_SIZE = 8 * 1024; public static final String readFully(final InputStream pInputStream) throws IOException { final StringBuilder sb = new StringBuilder(); final Scanner sc = new Scanner(pInputStream); while(sc.hasNextLine()) { sb.append(sc.nextLine()); } return sb.toString(); } }
Read Stream to byte array
//package org.anddev.andengine.util; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.util.Scanner; class StreamUtils { public static final int IO_BUFFER_SIZE = 8 * 1024; public static byte[] streamToBytes(final InputStream pInputStream) throws IOException { return StreamUtils.streamToBytes(pInputStream, -1); } public static byte[] streamToBytes(final InputStream pInputStream, final int pReadLimit) throws IOException { final ByteArrayOutputStream os = new ByteArrayOutputStream((pReadLimit == -1) ? IO_BUFFER_SIZE : pReadLimit); StreamUtils.copy(pInputStream, os, pReadLimit); return os.toByteArray(); } public static void copy(final InputStream pInputStream, final OutputStream pOutputStream) throws IOException { StreamUtils.copy(pInputStream, pOutputStream, -1); } public static void copy(final InputStream pInputStream, final OutputStream pOutputStream, final long pByteLimit) throws IOException { if(pByteLimit < 0) { final byte[] b = new byte[IO_BUFFER_SIZE]; int read; while((read = pInputStream.read(b)) != -1) { pOutputStream.write(b, 0, read); } } else { final byte[] b = new byte[IO_BUFFER_SIZE]; final int bufferReadLimit = Math.min((int)pByteLimit, IO_BUFFER_SIZE); long pBytesLeftToRead = pByteLimit; int read; while((read = pInputStream.read(b, 0, bufferReadLimit)) != -1) { if(pBytesLeftToRead > read) { pOutputStream.write(b, 0, read); pBytesLeftToRead -= read; } else { pOutputStream.write(b, 0, (int) pBytesLeftToRead); break; } } } pOutputStream.flush(); } }
read String From Stream
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; class Main { public static String readStringFromStream(InputStream stream) throws IOException { InputStreamReader isReader = new InputStreamReader(stream, Charset.forName("utf-8")); BufferedReader br = new BufferedReader(isReader); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } }
Read stream Fully
import java.io.ByteArrayOutputStream; import java.io.InputStream; class StreamUtils { public static byte[] readstreamFully(InputStream is) { return readstreamFully(is, 1024); } public static byte[] readstreamFully(InputStream is, int blocksize) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[blocksize]; while (true) { int len = is.read(buffer); if (len == -1) { break; } baos.write(buffer, 0, len); } return baos.toByteArray(); } catch (Exception e) { } return new byte[0]; } }
Read InputStream with ByteArrayOutputStream
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; class Main { public static String inputStream2String(InputStream inputStream) throws IOException{ byte[] buffer = new byte[8192]; int bytesRead; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); while((bytesRead = inputStream.read(buffer)) != -1){ outputStream.write(buffer, 0, bytesRead); } return outputStream.toString("US-ASCII"); } }