Java Code Examples for java.io.FileInputStream

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Absolute-Android-RSS, under directory /src/com/AA/Services/.

Source file: RssService.java

  19 
vote

/** 
 * Reads in data from the saved file.
 * @param context - Context that gives us some system access
 * @return - Returns the list of items that were saved; If there was problemwhen gathering this data, an empty list is returned
 */
@SuppressWarnings("unchecked") public static ArrayList<Article> readData(Context context){
  ArrayList<Article> oldList=new ArrayList<Article>();
  try {
    FileInputStream fileStream=context.openFileInput("articles");
    ObjectInputStream reader=new ObjectInputStream(fileStream);
    oldList=(ArrayList<Article>)reader.readObject();
    reader.close();
    fileStream.close();
    return oldList;
  }
 catch (  java.io.FileNotFoundException e) {
    return new ArrayList<Article>();
  }
catch (  IOException e) {
    Log.e("AARSS","Problem loading the file. Does it exists?",e);
    return new ArrayList<Article>();
  }
catch (  ClassNotFoundException e) {
    Log.e("AARSS","Problem converting data from file.",e);
    return new ArrayList<Article>();
  }
}
 

Example 2

From project aether-core, under directory /aether-test-util/src/main/java/org/eclipse/aether/internal/test/util/.

Source file: TestFileUtils.java

  19 
vote

public static void read(Properties props,File file) throws IOException {
  FileInputStream fis=null;
  try {
    fis=new FileInputStream(file);
    props.load(fis);
  }
  finally {
    close(fis);
  }
}
 

Example 3

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.

Source file: FileUtils.java

  18 
vote

public static void unJar(String path,String to,boolean verbose){
  File file=new File(path);
  Utils.console("Starting unjar of: " + file.getAbsolutePath() + File.separator+ "*.jar");
  if (file.exists()) {
    File[] files;
    if (file.isFile()) {
      files=new File[]{file};
    }
 else {
      files=file.listFiles();
    }
    for (int i=0; i < files.length; i++) {
      if (!files[i].isDirectory() && files[i].getName().endsWith("jar")) {
        Utils.console("unJar file: " + files[i].getName() + " ("+ (i + 1)+ "/"+ files.length+ ")");
        try {
          FileInputStream fis=new FileInputStream(files[i]);
          JarInputStream zis=new JarInputStream(new BufferedInputStream(fis));
          ZipEntry entry;
          while ((entry=zis.getNextEntry()) != null) {
            writejarEntry(zis,entry,to,false);
          }
          zis.close();
        }
 catch (        IOException e) {
          Utils.log("unJar error:",e);
        }
      }
    }
  }
 else {
    System.err.println("Failed to create: " + file.getAbsolutePath());
  }
}
 

Example 4

From project acceleo-webapp-generator, under directory /plugins/org.eclipse.acceleo.tutorial/src/org/eclipse/acceleo/tutorial/wizard/.

Source file: EclipseConWizard.java

  18 
vote

/** 
 * Reads and return the content of the given file as a String, given the charset name for this file's content.
 * @param file File we need to read.
 * @param charsetName Name of the charset we should use to read the file's content.
 * @return Content of the file, or the empty String if no such file exists.
 */
private static String readFileContent(File file,String charsetName){
  StringBuffer buffer=new StringBuffer();
  FileInputStream input=null;
  InputStreamReader streamReader=null;
  try {
    input=new FileInputStream(file);
    if (charsetName != null) {
      streamReader=new InputStreamReader(input,charsetName);
    }
 else {
      streamReader=new InputStreamReader(input);
    }
    int size=0;
    final int buffLength=8192;
    char[] buff=new char[buffLength];
    while ((size=streamReader.read(buff)) > 0) {
      buffer.append(buff,0,size);
    }
  }
 catch (  IOException e) {
  }
 finally {
    try {
      if (streamReader != null) {
        streamReader.close();
      }
      if (input != null) {
        input.close();
      }
    }
 catch (    IOException e) {
    }
  }
  return buffer.toString();
}
 

Example 5

From project accesointeligente, under directory /src/org/accesointeligente/server/.

Source file: ApplicationProperties.java

  18 
vote

@Override public void contextInitialized(ServletContextEvent event){
  try {
    properties=new Properties();
    properties.load(new FileInputStream(event.getServletContext().getRealPath("/WEB-INF/accesointeligente.properties")));
    logger.info("Context initialized");
  }
 catch (  Throwable ex) {
    logger.error("Failed to initialize context",ex);
  }
}
 

Example 6

From project AceWiki, under directory /src/ch/uzh/ifi/attempto/acewiki/core/.

Source file: FileBasedStorage.java

  18 
vote

private static User loadUser(UserBase userBase,File file){
  try {
    long id=new Long(file.getName());
    FileInputStream in=new FileInputStream(file);
    byte[] bytes=new byte[in.available()];
    in.read(bytes);
    in.close();
    String s=new String(bytes,"UTF-8");
    String[] lines=s.split("\n");
    if (lines.length < 2 || !lines[0].startsWith("name:") || !lines[1].startsWith("pw:")) {
      System.err.println("Invalid user file: " + id);
      return null;
    }
    String name=lines[0].substring("name:".length());
    String pw=lines[1].substring("pw:".length());
    if (pw.startsWith("\"") && pw.endsWith("\"")) {
      pw=User.getPasswordHash(pw.substring(1,pw.length() - 1));
    }
    Map<String,String> userdata=new HashMap<String,String>();
    for (int i=2; i < lines.length; i++) {
      String l=lines[i];
      int p=l.indexOf(":");
      if (p > -1) {
        String n=l.substring(0,p);
        String v=l.substring(p + 1);
        userdata.put(n,v);
      }
    }
    return new User(id,name,pw,userdata,userBase);
  }
 catch (  NumberFormatException ex) {
    System.err.println("ignoring user file: " + file.getName());
  }
catch (  IOException ex) {
    System.err.println("cannot read user file: " + file.getName());
  }
  return null;
}
 

Example 7

From project agile, under directory /agile-framework/src/main/java/org/apache/naming/resources/.

Source file: FileDirContext.java

  18 
vote

/** 
 * Content accessor.
 * @return InputStream
 */
public InputStream streamContent() throws IOException {
  if (binaryContent == null) {
    FileInputStream fis=new FileInputStream(file);
    inputStream=fis;
    return fis;
  }
  return super.streamContent();
}
 

Example 8

From project ambrose, under directory /common/src/main/java/com/twitter/ambrose/util/.

Source file: JSONUtil.java

  18 
vote

public static String readFile(String path) throws IOException {
  FileInputStream stream=new FileInputStream(new File(path));
  try {
    FileChannel fc=stream.getChannel();
    MappedByteBuffer bb=fc.map(FileChannel.MapMode.READ_ONLY,0,fc.size());
    return Charset.defaultCharset().decode(bb).toString();
  }
  finally {
    stream.close();
  }
}
 

Example 9

From project android-sdk, under directory /src/test/java/com/mobeelizer/mobile/android/.

Source file: MobeelizerFileImplTest.java

  18 
vote

@Test public void shouldAddFile() throws Exception {
  ByteArrayInputStream stream=new ByteArrayInputStream(new byte[0]);
  when(fileService.addFile(stream)).thenReturn("guid");
  File file=mock(File.class);
  when(file.exists()).thenReturn(true);
  when(file.canRead()).thenReturn(true);
  when(fileService.getFile("guid")).thenReturn(file);
  FileInputStream fileStream=mock(FileInputStream.class);
  PowerMockito.whenNew(FileInputStream.class).withArguments(file).thenReturn(fileStream);
  MobeelizerFileImpl mobeelizerFile=new MobeelizerFileImpl("name",stream);
  assertEquals("guid",mobeelizerFile.getGuid());
  assertEquals("name",mobeelizerFile.getName());
  assertEquals(fileStream,mobeelizerFile.getInputStream());
}
 

Example 10

From project androidquery, under directory /demo/src/com/androidquery/test/.

Source file: AdhocActivity.java

  18 
vote

private Bitmap decode(File file) throws Exception {
  BitmapFactory.Options options=new Options();
  options.inInputShareable=true;
  options.inPurgeable=true;
  FileInputStream fis=new FileInputStream(file);
  Bitmap result=BitmapFactory.decodeFileDescriptor(fis.getFD(),null,options);
  AQUtility.debug("bm",result.getWidth() + "x" + result.getHeight());
  fis.close();
  return result;
}
 

Example 11

From project android_5, under directory /src/aarddict/android/.

Source file: DictionariesActivity.java

  18 
vote

@SuppressWarnings("unchecked") void loadVerifyData() throws IOException, ClassNotFoundException {
  File verifyDir=getDir("verify",0);
  File verifyFile=new File(verifyDir,"verifydata");
  if (verifyFile.exists()) {
    FileInputStream fin=new FileInputStream(verifyFile);
    ObjectInputStream oin=new ObjectInputStream(fin);
    verifyData=(Map<UUID,VerifyRecord>)oin.readObject();
  }
}
 

Example 12

From project android_build, under directory /tools/signapk/.

Source file: SignApk.java

  18 
vote

private static X509Certificate readPublicKey(File file) throws IOException, GeneralSecurityException {
  FileInputStream input=new FileInputStream(file);
  try {
    CertificateFactory cf=CertificateFactory.getInstance("X.509");
    return (X509Certificate)cf.generateCertificate(input);
  }
  finally {
    input.close();
  }
}
 

Example 13

From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Manager/.

Source file: StructureManager.java

  17 
vote

public ArrayList<StructureBlock> loadStructure(String structureName){
  ArrayList<StructureBlock> blockList=new ArrayList<StructureBlock>();
  try {
    File folder=new File("plugins/16Blocks/structures");
    folder.mkdirs();
    File file=new File(folder,structureName + ".dat");
    if (!file.exists())     return null;
    FileInputStream fileInputStream=new FileInputStream(file);
    ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
    int length=objectInputStream.readInt();
    byte[] xArray=new byte[length];
    byte[] yArray=new byte[length];
    byte[] zArray=new byte[length];
    byte[] IDArray=new byte[length];
    byte[] SubIDArray=new byte[length];
    xArray=(byte[])objectInputStream.readObject();
    yArray=(byte[])objectInputStream.readObject();
    zArray=(byte[])objectInputStream.readObject();
    IDArray=(byte[])objectInputStream.readObject();
    SubIDArray=(byte[])objectInputStream.readObject();
    objectInputStream.close();
    fileInputStream.close();
    for (int i=0; i < length; i++) {
      blockList.add(new StructureBlock(xArray[i],yArray[i],zArray[i],IDArray[i],SubIDArray[i]));
    }
    return blockList.size() > 0 ? blockList : null;
  }
 catch (  Exception e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 14

From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/config/.

Source file: JsonConfigLoader.java

  17 
vote

/** 
 * Load the configuration from a file.
 * @param configFile
 * @return the configuration or null if it couldn't be found / read.
 * @throws ConfigurationException 
 */
public C loadConfiguration(String configFile) throws ConfigurationException {
  InputStream is=null;
  try {
    File cf=new File(configFile == null ? "config.json" : configFile);
    is=new FileInputStream(cf);
    return readConfiguration(is);
  }
 catch (  IOException ex) {
    throw new ConfigurationException("Cannot open file '" + configFile + "'",ex);
  }
 finally {
    closeQuietly(is);
  }
}
 

Example 15

From project addis, under directory /application/src/main/java/org/drugis/addis/gui/.

Source file: Main.java

  17 
vote

private boolean loadDomainFromXMLFile(String fileName){
  File f=new File(fileName);
  if (f.exists() && f.isFile()) {
    try {
      FileInputStream in=new FileInputStream(f);
      d_xmlType=loadDomainFromInputStream(in);
    }
 catch (    Exception e) {
      ErrorDialog.showDialog(e,"Error loading file","Error loading data from \"" + fileName + "\"",false);
      return false;
    }
    if (!d_xmlType.isValid()) {
      JOptionPane.showMessageDialog(s_window,"The file you are attempting to load is not formatted as a valid ADDIS XML file.","Error loading file",JOptionPane.ERROR_MESSAGE);
      return false;
    }
 else     if (d_xmlType.isFuture()) {
      JOptionPane.showMessageDialog(s_window,"The XML file was created with a newer version of ADDIS than you are using. Please download the new version to read it.","Error loading file",JOptionPane.ERROR_MESSAGE);
      return false;
    }
 else     if (d_xmlType.isLegacy()) {
      askToConvertToNew(fileName);
      return true;
    }
 else {
      setFileNameAndReset(fileName);
      return true;
    }
  }
 else {
    JOptionPane.showMessageDialog(s_window,"File \"" + fileName + "\" not found.","Error loading file",JOptionPane.ERROR_MESSAGE);
    return false;
  }
}
 

Example 16

From project AdminCmd, under directory /src/main/java/be/Balor/Tools/Configuration/File/.

Source file: ExFileConfiguration.java

  17 
vote

/** 
 * Loads this  {@link ExFileConfiguration} from the specified location.<p> All the values contained within this configuration will be removed, leaving only settings and defaults, and the new values will be loaded from the given file. <p> If the file cannot be loaded for any reason, an exception will be thrown.
 * @param file File to load from.
 * @throws FileNotFoundException Thrown when the given file cannot be opened.
 * @throws IOException Thrown when the given file cannot be read.
 * @throws InvalidConfigurationException Thrown when the given file is not a valid Configuration.
 * @throws IllegalArgumentException Thrown when file is null.
 */
public void load(final File file) throws FileNotFoundException, IOException, InvalidConfigurationException {
  if (file == null) {
    throw new IllegalArgumentException("File cannot be null");
  }
  this.file=file;
  try {
    load(new FileInputStream(this.file));
  }
 catch (  final IllegalArgumentException e) {
    ACLogger.severe("Problem with File : " + this.file);
    ACLogger.severe(e.getLocalizedMessage(),e);
  }
}
 

Example 17

From project AdServing, under directory /modules/utilities/common/src/main/java/net/mad/ads/common/util/.

Source file: Properties2.java

  17 
vote

static public Properties loadProperties(File propertiesFile) throws IOException {
  InputStream is=null;
  is=new FileInputStream(propertiesFile);
  Properties prop=new Properties();
  prop.load(is);
  return new XProperties(prop);
}
 

Example 18

From project Agot-Java, under directory /src/main/java/got/utility/.

Source file: ConnectionCreate.java

  17 
vote

/** 
 * loadCenters() Loads a pre-defined file with map center points.
 */
private void loadCenters(){
  try {
    System.out.println("Load a center file");
    final String centerName=new FileOpen("Load A Center File").getPathString();
    if (centerName == null) {
      return;
    }
    final FileInputStream in=new FileInputStream(centerName);
    m_centers=PointFileReaderWriter.readOneToOne(in);
    repaint();
  }
 catch (  final FileNotFoundException ex) {
    ex.printStackTrace();
  }
catch (  final IOException ex) {
    ex.printStackTrace();
  }
catch (  final HeadlessException ex) {
    ex.printStackTrace();
  }
}
 

Example 19

From project agraph-java-client, under directory /src/test/.

Source file: AGMoreJenaExamples.java

  17 
vote

public static void addModelToAGModel() throws Exception {
  AGGraphMaker maker=example1(false);
  AGModel agmodel=new AGModel(maker.createGraph());
  OntModel model=ModelFactory.createOntologyModel(new OntModelSpec(OntModelSpec.OWL_DL_MEM));
  model.read(new FileInputStream("src/tutorial/java-lesmis.rdf"),null);
  println("Read " + model.size() + " lesmis.rdf triples.");
  agmodel.add(model);
  println("Add yields " + agmodel.size() + " triples in agmodel.");
}
 

Example 20

From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/GeoData/.

Source file: GeoEngine.java

  17 
vote

private void parseFile(File f){
  int mapId=WorldMapType.getShortIdByWorldId(Integer.parseInt(f.getName().replace(".aion.geo","")));
  FileInputStream in=null;
  try {
    in=new FileInputStream(f);
    byte[] data=new byte[in.available()];
    in.read(data);
    int byteRate=24 / 8;
    for (int i=0; i < 1536; i++) {
      for (int j=0; j < 1536; j++) {
        byte pointData[]=new byte[byteRate];
        System.arraycopy(data,(i * 1536 + j) * byteRate,pointData,0,byteRate);
        _content[mapId][j][i]=makeValue(pointData);
      }
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
 finally {
    try {
      if (in != null)       in.close();
    }
 catch (    IOException e) {
    }
  }
}
 

Example 21

From project Airports, under directory /src/com/nadmm/airports/utils/.

Source file: FileUtils.java

  17 
vote

public static String readFile(String path) throws IOException {
  FileInputStream is=new FileInputStream(path);
  try {
    StringBuilder sb=new StringBuilder();
    Reader reader=new BufferedReader(new InputStreamReader(is));
    char[] buffer=new char[8192];
    int read;
    while ((read=reader.read(buffer)) > 0) {
      sb.append(buffer,0,read);
    }
    return sb.toString();
  }
  finally {
    is.close();
  }
}
 

Example 22

From project ajah, under directory /ajah-util/src/main/java/com/ajah/util/io/file/.

Source file: FileUtils.java

  17 
vote

/** 
 * Reads a file into a byte array.
 * @param file The file to read, required.
 * @return The data in the file as a byte array.
 * @throws IOException If the file could not be read.
 */
public static byte[] readFileAsBytes(final File file) throws IOException {
  AjahUtils.requireParam(file,"file");
  if (!file.exists()) {
    throw new FileNotFoundException(file.getAbsolutePath());
  }
  final FileInputStream in=new FileInputStream(file);
  final ByteArrayOutputStream baos=new ByteArrayOutputStream();
  final DataOutputStream dos=new DataOutputStream(baos);
  final byte[] data=new byte[4096];
  int count=in.read(data);
  while (count != -1) {
    dos.write(data,0,count);
    count=in.read(data);
  }
  return baos.toByteArray();
}
 

Example 23

From project akubra, under directory /akubra-fs/src/main/java/org/akubraproject/fs/.

Source file: FSBlob.java

  17 
vote

private static void nioCopy(File source,File dest) throws IOException {
  FileInputStream f_in=null;
  FileOutputStream f_out=null;
  log.debug("Performing force copy-and-delete of source '" + source + "' to '"+ dest+ "'");
  try {
    f_in=new FileInputStream(source);
    try {
      f_out=new FileOutputStream(dest);
      FileChannel in=f_in.getChannel();
      FileChannel out=f_out.getChannel();
      in.transferTo(0,source.length(),out);
    }
  finally {
      IOUtils.closeQuietly(f_out);
    }
  }
  finally {
    IOUtils.closeQuietly(f_in);
  }
  if (!dest.exists())   throw new IOException("Failed to copy file to new location: " + dest);
}
 

Example 24

From project AlarmApp-Android, under directory /src/org/alarmapp/util/.

Source file: RingtoneUtil.java

  17 
vote

/** 
 * returns the file descriptor of the newly installed Ringtone
 */
private static File writeToSDCard(int ressourceId,String fileName) throws IOException {
  File newSoundFile=new File(ALARMS_DIR,fileName);
  if (!doesAlarmDirExsist()) {
    if (!new File(ALARMS_DIR).mkdirs())     throw new IOException("Failed to create the Ringtone dir");
  }
 else   if (newSoundFile.exists()) {
    LogEx.verbose("Sound file " + fileName + " does already exist.");
    return newSoundFile;
  }
  LogEx.verbose("android.resource://org.alarmapp/" + ressourceId);
  Uri mUri=Uri.parse("android.resource://org.alarmapp/" + ressourceId);
  ContentResolver mCr=AlarmApp.getInstance().getContentResolver();
  AssetFileDescriptor soundFile;
  soundFile=mCr.openAssetFileDescriptor(mUri,"r");
  byte[] readData=new byte[1024];
  FileInputStream fis=soundFile.createInputStream();
  FileOutputStream fos=new FileOutputStream(newSoundFile);
  int i=fis.read(readData);
  while (i != -1) {
    fos.write(readData,0,i);
    i=fis.read(readData);
  }
  fos.close();
  return newSoundFile;
}
 

Example 25

From project ALP, under directory /workspace/alp-utils/src/main/java/com/lohika/alp/utils/zip/.

Source file: Zip.java

  17 
vote

/** 
 * Adds file to Zip.
 * @param filePath the file path
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void add(String filePath) throws IOException {
  byte data[]=new byte[BUFFER];
  File f=new File(filePath);
  if (f.isDirectory()) {
    File files[]=f.listFiles();
    for (int i=0; i < files.length; i++) {
      add(files[i].getAbsolutePath());
    }
  }
 else {
    logger.debug("Adding: " + filePath);
    FileInputStream fi=new FileInputStream(filePath);
    BufferedInputStream origin=new BufferedInputStream(fi,BUFFER);
    ZipEntry entry=new ZipEntry(filePath);
    out.putNextEntry(entry);
    int count;
    while ((count=origin.read(data,0,BUFFER)) != -1) {
      out.write(data,0,count);
    }
    origin.close();
  }
  logger.debug("checksum: " + checksum.getChecksum().getValue());
}
 

Example 26

From project anadix, under directory /anadix-api/src/main/java/org/anadix/factories/.

Source file: FileSource.java

  17 
vote

/** 
 * {@inheritDoc}
 */
public InputStream getStream(){
  try {
    return new FileInputStream(source);
  }
 catch (  FileNotFoundException e) {
    LoggerFactory.getLogger(getClass()).error("Unable to find file",e);
    throw new RuntimeException("Unable to find file",e);
  }
}
 

Example 27

From project and-bible, under directory /AndBible/src/net/bible/service/common/.

Source file: CommonUtils.java

  17 
vote

public static Properties loadProperties(File propertiesFile){
  Properties properties=new Properties();
  if (propertiesFile.exists()) {
    FileInputStream in=null;
    try {
      in=new FileInputStream(propertiesFile);
      properties.load(in);
    }
 catch (    Exception e) {
      Log.e(TAG,"Error loading properties",e);
    }
 finally {
      IOUtil.close(in);
    }
  }
  return properties;
}
 

Example 28

From project andlytics, under directory /src/com/github/andlyticsproject/io/.

Source file: StatsCsvReaderWriter.java

  17 
vote

public String readPackageName(String fileName) throws ServiceExceptoin {
  try {
    return readPackageName(new FileInputStream(new File(getExportDirPath(),fileName)));
  }
 catch (  IOException e) {
    throw new ServiceExceptoin(e);
  }
}
 

Example 29

From project android-aac-enc, under directory /src/com/todoroo/aacenc/.

Source file: AACToM4A.java

  17 
vote

public void convert(Context context,String infile,String outfile) throws IOException {
  AACToM4A.context=context;
  InputStream input=new FileInputStream(infile);
  PushbackInputStream pbi=new PushbackInputStream(input,100);
  System.err.println("well you got " + input.available());
  Movie movie=new Movie();
  Track audioTrack=new AACTrackImpl(pbi);
  movie.addTrack(audioTrack);
  IsoFile out=new DefaultMp4Builder().build(movie);
  FileOutputStream output=new FileOutputStream(outfile);
  out.getBox(output.getChannel());
  output.close();
}
 

Example 30

From project android-api_1, under directory /android-lib/src/com/android/http/multipart/.

Source file: FilePartSource.java

  17 
vote

/** 
 * Return a new  {@link FileInputStream} for the current filename.
 * @return the new input stream.
 * @throws IOException If an IO problem occurs.
 * @see PartSource#createInputStream()
 */
public InputStream createInputStream() throws IOException {
  if (this.file != null) {
    return new FileInputStream(this.file);
  }
 else {
    return new ByteArrayInputStream(new byte[]{});
  }
}
 

Example 31

From project android-async-http, under directory /src/com/loopj/android/http/.

Source file: SimpleMultipartEntity.java

  17 
vote

public void addPart(final String key,final File value,final boolean isLast){
  try {
    addPart(key,value.getName(),new FileInputStream(value),isLast);
  }
 catch (  final FileNotFoundException e) {
    e.printStackTrace();
  }
}
 

Example 32

From project android-client, under directory /xwiki-android-test-core/src/org/xwiki/android/rest/ral/test/.

Source file: TestDocumentRaoCreate.java

  17 
vote

@Override public void setUp() throws Exception {
  super.setUp();
  username=TestConstants.USERNAME;
  password=TestConstants.PASSWORD;
  serverUrl=TestConstants.SERVER_URL;
  wikiName=TestConstants.WIKI_NAME;
  spaceName=TestConstants.SPACE_NAME;
  pageName=TestConstants.CREATE_PAGE_NAME + "-" + count;
  attachmentName=TestConstants.ATTACHMENT_NAME;
  objClsName1=TestConstants.OBJECT_CLASS_NAME_1;
  objClsName2=TestConstants.OBJECT_CLASS_NAME_2;
  rm=new XmlRESTFulManager(serverUrl,username,password);
  api=rm.getRestConnector();
  rao=rm.newDocumentRao();
  doc=new Document(wikiName,spaceName,pageName);
  doc.setTitle(pageName);
  api.deletePage(wikiName,spaceName,pageName);
  if (count == 9) {
    Application sys=XWikiApplicationContext.getInstance();
    FileOutputStream fos=sys.openFileOutput(attachmentName,Context.MODE_WORLD_READABLE);
    PrintWriter writer=new PrintWriter(fos);
    writer.println("this is a text attachment.");
    writer.flush();
    writer.close();
    FileInputStream fis=sys.openFileInput(attachmentName);
    byte[] buff=new byte[30];
    int i=0;
    while (i != -1) {
      i=fis.read(buff);
    }
    Log.d(TAG,new String(buff));
    af1=sys.getFileStreamPath(attachmentName);
  }
  Log.d(TAG,"setup test method:" + count);
}
 

Example 33

From project Android-FFXIEQ, under directory /ffxieq/src/com/github/kanata3249/ffxieq/android/db/.

Source file: FFXIDatabase.java

  17 
vote

void copyDatabaseFromSD(String sd_path) throws IOException {
  File outDir=new File(DB_PATH);
  outDir.mkdir();
  FileChannel channelSource=new FileInputStream(sd_path + DB_NAME).getChannel();
  FileChannel channelTarget=new FileOutputStream(DB_PATH + DB_NAME).getChannel();
  channelSource.transferTo(0,channelSource.size(),channelTarget);
  channelSource.close();
  channelTarget.close();
  File from=new File(sd_path + DB_NAME);
  File to=new File(DB_PATH + DB_NAME);
  to.setLastModified(from.lastModified());
}
 

Example 34

From project Android-File-Manager-Tablet, under directory /src/com/nexes/manager/tablet/.

Source file: BluetoothActivity.java

  17 
vote

private void communicateData(BluetoothSocket socket){
  OutputStream writeStrm=null;
  FileInputStream readStrm=null;
  int len=mFilePaths.length;
  byte[] buffer=new byte[1024];
  Log.e("ClientSocketThread","communicateData is called");
  try {
    for (int i=0; i < len; i++) {
      File file=new File(mFilePaths[i]);
      writeStrm=socket.getOutputStream();
      readStrm=new FileInputStream(file);
      int read=0;
      Message msg=new Message();
      msg.obj=(String)file.getName();
      msg.arg2=(int)file.length();
      while ((read=readStrm.read(buffer)) != -1) {
        msg.arg1=read;
        msg.what=DIALOG_UPDATE;
        writeStrm.write(buffer);
        mHandle.sendMessage(msg);
      }
      Log.e("OPENMANAGER","file is done");
    }
    writeStrm.close();
    cancel();
  }
 catch (  IOException e) {
    Message msg=mHandle.obtainMessage();
    msg.obj=e.getMessage();
    msg.what=DIALOG_CANCEL;
    mHandle.sendMessage(msg);
  }
}
 

Example 35

From project Android-GifStitch, under directory /src/com/phunkosis/gifstitch/settings/.

Source file: GSSettings.java

  17 
vote

public static void copyFile(File srcFile,File destFile) throws IOException {
  InputStream oInStream=new FileInputStream(srcFile);
  OutputStream oOutStream=new FileOutputStream(destFile);
  byte[] oBytes=new byte[1024];
  int nLength;
  BufferedInputStream oBuffInputStream=new BufferedInputStream(oInStream);
  while ((nLength=oBuffInputStream.read(oBytes)) > 0) {
    oOutStream.write(oBytes,0,nLength);
  }
  oInStream.close();
  oOutStream.close();
}
 

Example 36

From project android-joedayz, under directory /Proyectos/Archivos/src/net/ivanvega/Archivos/.

Source file: MainActivity.java

  17 
vote

@Override public void onClick(View arg0){
  if (arg0.equals(btnGuardar)) {
    String str=txtTexto.getText().toString();
    FileOutputStream fout=null;
    try {
      fout=openFileOutput("archivoTexto.txt",MODE_WORLD_READABLE);
      OutputStreamWriter ows=new OutputStreamWriter(fout);
      ows.write(str);
      ows.flush();
      ows.close();
    }
 catch (    IOException e) {
      e.printStackTrace();
    }
    Toast.makeText(getBaseContext(),"El archivo se ha almacenado!!!",Toast.LENGTH_SHORT).show();
    txtTexto.setText("");
  }
  if (arg0.equals(btnAbrir)) {
    try {
      FileInputStream fin=openFileInput("archivoTexto.txt");
      InputStreamReader isr=new InputStreamReader(fin);
      char[] inputBuffer=new char[READ_BLOCK_SIZE];
      String str="";
      int charRead;
      while ((charRead=isr.read(inputBuffer)) > 0) {
        String strRead=String.copyValueOf(inputBuffer,0,charRead);
        str+=strRead;
        inputBuffer=new char[READ_BLOCK_SIZE];
      }
      txtTexto.setText(str);
      isr.close();
      Toast.makeText(getBaseContext(),"El archivo ha sido cargado",Toast.LENGTH_SHORT).show();
    }
 catch (    IOException e) {
      e.printStackTrace();
    }
  }
}
 

Example 37

From project Android-MapForgeFragment, under directory /library-common/src/com/jakewharton/android/mapsforge_fragment/.

Source file: TileMemoryCardCache.java

  17 
vote

/** 
 * Restores the serialized cache map if possible.
 * @return true if the map was restored successfully, false otherwise.
 */
@SuppressWarnings("unchecked") private synchronized boolean deserializeCacheMap(){
  try {
    File file=new File(this.tempDir,SERIALIZATION_FILE_NAME);
    if (!file.exists()) {
      return false;
    }
 else     if (!file.isFile()) {
      return false;
    }
 else     if (!file.canRead()) {
      return false;
    }
    FileInputStream inputStream=new FileInputStream(file);
    ObjectInputStream objectInputStream=new ObjectInputStream(inputStream);
    this.map=(Map<MapGeneratorJob,File>)objectInputStream.readObject();
    objectInputStream.close();
    inputStream.close();
    if (!file.delete()) {
      file.deleteOnExit();
    }
    return true;
  }
 catch (  IOException e) {
    Logger.exception(e);
    return false;
  }
catch (  ClassNotFoundException e) {
    Logger.exception(e);
    return false;
  }
}
 

Example 38

From project android-rackspacecloud, under directory /src/com/rackspacecloud/android/.

Source file: ListAccountsActivity.java

  17 
vote

private ArrayList<Account> readAccounts(){
  FileInputStream fis;
  ObjectInputStream in;
  try {
    fis=openFileInput(FILENAME);
    in=new ObjectInputStream(fis);
    @SuppressWarnings("unchecked") ArrayList<Account> file=(ArrayList<Account>)in.readObject();
    in.close();
    return file;
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
    return null;
  }
catch (  StreamCorruptedException e) {
    showAlert("Error","Could not load accounts.");
    e.printStackTrace();
  }
catch (  IOException e) {
    showAlert("Error","Could not load accounts.");
    e.printStackTrace();
  }
catch (  ClassNotFoundException e) {
    showAlert("Error","Could not load accounts.");
    e.printStackTrace();
  }
  return null;
}
 

Example 39

From project android-rindirect, under directory /rindirect/src/test/java/de/akquinet/android/rindirect/.

Source file: RindirectTest.java

  17 
vote

@BeforeClass public static void configure() throws FileNotFoundException, IOException {
  File template=new File("src/main/resources/templates/R.vm");
  File out=new File("target/test-classes/templates");
  out.mkdirs();
  out=new File("target/test-classes/templates/R.vm");
  copyInputStream(new FileInputStream(template),new FileOutputStream(out));
}
 

Example 40

From project Android-RTMP, under directory /android-ffmpeg-prototype/src/com/camundo/media/pipe/.

Source file: FileAudioOutputPipe.java

  17 
vote

@Override public void start(){
  try {
    inputStream=new FileInputStream(file);
    WavInfo w=AudioCodec.WaveFile.readHeader(inputStream);
    this.sampleRate=w.rate;
    this.channels=w.channels;
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 41

From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/preference/activity/.

Source file: PreferencesRestoreBackupActivity.java

  17 
vote

public Void doInBackground(String... filename){
  try {
    String message=getString(R.string.status_reading_backup);
    Log.d(cTag,message);
    publishProgress(Progress.createProgress(5,message));
    File dir=Environment.getExternalStorageDirectory();
    File backupFile=new File(dir,filename[0]);
    FileInputStream in=new FileInputStream(backupFile);
    Catalogue catalogue=Catalogue.parseFrom(in);
    in.close();
    Log.d(cTag,catalogue.toString());
    EntityDirectory<Context> contextLocator=addContexts(catalogue.getContextList(),10,20);
    EntityDirectory<Project> projectLocator=addProjects(catalogue.getProjectList(),contextLocator,20,30);
    addTasks(catalogue.getTaskList(),contextLocator,projectLocator,30,100);
    message=getString(R.string.status_restore_complete);
    publishProgress(Progress.createProgress(100,message));
  }
 catch (  Exception e) {
    String message=getString(R.string.warning_restore_failed,e.getMessage());
    reportError(message);
  }
  return null;
}
 

Example 42

From project Android-SQL-Helper, under directory /src/com/sgxmobileapps/androidsqlhelper/processor/model/.

Source file: Schema.java

  17 
vote

/** 
 * Loads properties values from a Properties class
 * @param props the properties class
 * @throws IOException 
 */
public void loadSchemaPropeties(Properties props) throws IOException {
  mPackage=props.getProperty(KEY_PACKAGE,DEFAULT_PACKAGE);
  mDbAdapterClassName=props.getProperty(KEY_ADAPTER_CLASS_NAME,DEFAULT_ADAPTER_CLASS_NAME);
  mMetadataClassName=props.getProperty(KEY_METADATA_CLASS_NAME,DEFAULT_METADATA_CLASS_NAME);
  mDbName=props.getProperty(KEY_DB_NAME,DEFAULT_DB_NAME);
  mDbVersion=props.getProperty(KEY_DB_VERSION,DEFAULT_DB_VERSION);
  mAuthor=props.getProperty(KEY_AUTHOR,DEFAULT_AUTHOR);
  mLicense=props.getProperty(KEY_LICENSE,DEFAULT_LICENSE);
  mLicenseFile=props.getProperty(KEY_LICENSE_FILE,DEFAULT_LICENSE_FILE);
  if (!mLicenseFile.isEmpty()) {
    FileInputStream file=null;
    try {
      byte[] buffer=new byte[(int)new File(mLicenseFile).length()];
      file=new FileInputStream(mLicenseFile);
      file.read(buffer);
      mLicense=new String(buffer);
    }
  finally {
      file.close();
    }
  }
}
 

Example 43

From project android-tether, under directory /src/og/android/tether/system/.

Source file: Configuration.java

  17 
vote

public static boolean hasKernelFeature(String feature){
  try {
    File cfg=new File("/proc/config.gz");
    if (cfg.exists() == false) {
      return true;
    }
    FileInputStream fis=new FileInputStream(cfg);
    GZIPInputStream gzin=new GZIPInputStream(fis);
    BufferedReader in=null;
    String line="";
    in=new BufferedReader(new InputStreamReader(gzin));
    while ((line=in.readLine()) != null) {
      if (line.startsWith(feature)) {
        gzin.close();
        return true;
      }
    }
    gzin.close();
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  return false;
}
 

Example 44

From project android-xbmcremote, under directory /src/org/xbmc/eventclient/.

Source file: EventClient.java

  17 
vote

/** 
 * Sets the icon using a path name to a image file (png, jpg or gif).
 * @param iconPath Path to icon
 */
public void setIcon(String iconPath){
  byte iconType=Packet.ICON_PNG;
  if (iconPath.toLowerCase().endsWith(".jpeg"))   iconType=Packet.ICON_JPEG;
  if (iconPath.toLowerCase().endsWith(".jpg"))   iconType=Packet.ICON_JPEG;
  if (iconPath.toLowerCase().endsWith(".gif"))   iconType=Packet.ICON_GIF;
  FileInputStream iconFileStream;
  byte[] iconData;
  try {
    iconFileStream=new FileInputStream(iconPath);
    iconData=new byte[iconFileStream.available()];
    iconFileStream.read(iconData);
  }
 catch (  IOException e) {
    mHasIcon=false;
    return;
  }
  mHasIcon=true;
  setIcon(iconType,iconData);
}
 

Example 45

From project AndroidCommon, under directory /src/com/asksven/android/common/utils/.

Source file: DataStorage.java

  17 
vote

public static Object fileToObject(Context context,String fileName){
  FileInputStream fis;
  Object myRet=null;
  try {
    fis=context.openFileInput(fileName);
    ObjectInputStream is=new ObjectInputStream(fis);
    myRet=is.readObject();
    is.close();
  }
 catch (  FileNotFoundException e) {
    myRet=null;
  }
catch (  IOException e) {
    myRet=null;
  }
catch (  ClassNotFoundException e) {
    myRet=null;
  }
  return myRet;
}
 

Example 46

From project androidZenWriter, under directory /src/com/javaposse/android/zenwriter/.

Source file: AndroidZenWriterActivity.java

  17 
vote

protected void loadFile(String filename){
  FileInputStream fis=null;
  BufferedReader br=null;
  File file=getFileStreamPath(filename);
  StringBuilder content=new StringBuilder();
  if (file.exists()) {
    EditText editText=(EditText)findViewById(R.id.editText1);
    try {
      fis=openFileInput(filename);
      br=new BufferedReader(new InputStreamReader(fis));
      while (br.ready()) {
        content.append(br.readLine()).append("\n");
      }
      editText.setText(content.toString());
      editText.setSelection(content.length());
    }
 catch (    IOException e) {
      Log.e("SaveFile","Failed to save file: ",e);
    }
 finally {
      if (br != null) {
        try {
          br.close();
        }
 catch (        IOException e) {
        }
      }
      if (fis != null) {
        try {
          fis.close();
        }
 catch (        IOException e) {
        }
      }
    }
  }
}
 

Example 47

From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/applications/.

Source file: RunningProcessesView.java

  17 
vote

private long readAvailMem(){
  try {
    long memFree=0;
    long memCached=0;
    FileInputStream is=new FileInputStream("/proc/meminfo");
    int len=is.read(mBuffer);
    is.close();
    final int BUFLEN=mBuffer.length;
    for (int i=0; i < len && (memFree == 0 || memCached == 0); i++) {
      if (matchText(mBuffer,i,"MemFree")) {
        i+=7;
        memFree=extractMemValue(mBuffer,i);
      }
 else       if (matchText(mBuffer,i,"Cached")) {
        i+=6;
        memCached=extractMemValue(mBuffer,i);
      }
      while (i < BUFLEN && mBuffer[i] != '\n') {
        i++;
      }
    }
    return memFree + memCached;
  }
 catch (  java.io.FileNotFoundException e) {
  }
catch (  java.io.IOException e) {
  }
  return 0;
}
 

Example 48

From project android_external_guava, under directory /src/com/google/common/io/.

Source file: FileBackedOutputStream.java

  17 
vote

private synchronized InputStream openStream() throws IOException {
  if (file != null) {
    return new FileInputStream(file);
  }
 else {
    return new ByteArrayInputStream(memory.getBuffer(),0,memory.getCount());
  }
}
 

Example 49

From project android_packages_apps_FileManager, under directory /src/org/openintents/filemanager/.

Source file: FileManagerActivity.java

  17 
vote

private boolean copy(File oldFile,File newFile){
  try {
    FileInputStream input=new FileInputStream(oldFile);
    FileOutputStream output=new FileOutputStream(newFile);
    byte[] buffer=new byte[COPY_BUFFER_SIZE];
    while (true) {
      int bytes=input.read(buffer);
      if (bytes <= 0) {
        break;
      }
      output.write(buffer,0,bytes);
    }
    output.close();
    input.close();
  }
 catch (  Exception e) {
    return false;
  }
  return true;
}
 

Example 50

From project android_packages_apps_Gallery, under directory /src/com/android/camera/.

Source file: ThumbnailController.java

  17 
vote

public boolean loadData(String filePath){
  FileInputStream f=null;
  BufferedInputStream b=null;
  DataInputStream d=null;
  try {
    f=new FileInputStream(filePath);
    b=new BufferedInputStream(f,BUFSIZE);
    d=new DataInputStream(b);
    Uri uri=Uri.parse(d.readUTF());
    Bitmap thumb=BitmapFactory.decodeStream(d);
    setData(uri,thumb);
    d.close();
  }
 catch (  IOException e) {
    return false;
  }
 finally {
    MenuHelper.closeSilently(f);
    MenuHelper.closeSilently(b);
    MenuHelper.closeSilently(d);
  }
  return true;
}
 

Example 51

From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/data/.

Source file: BytesBufferPool.java

  17 
vote

public void readFrom(JobContext jc,FileDescriptor fd) throws IOException {
  FileInputStream fis=new FileInputStream(fd);
  length=0;
  try {
    int capacity=data.length;
    while (true) {
      int step=Math.min(READ_STEP,capacity - length);
      int rc=fis.read(data,length,step);
      if (rc < 0 || jc.isCancelled())       return;
      length+=rc;
      if (length == capacity) {
        byte[] newData=new byte[data.length * 2];
        System.arraycopy(data,0,newData,0,data.length);
        data=newData;
        capacity=data.length;
      }
    }
  }
  finally {
    fis.close();
  }
}
 

Example 52

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.

Source file: UriTexture.java

  17 
vote

public static boolean isCached(long crc64,int maxResolution){
  String file=null;
  if (crc64 != 0) {
    file=createFilePathFromCrc64(crc64,maxResolution);
    try {
      new FileInputStream(file);
      return true;
    }
 catch (    FileNotFoundException e) {
      return false;
    }
  }
  return false;
}
 

Example 53

From project android_packages_apps_Superuser, under directory /src/com/noshufou/android/su/util/.

Source file: BackupUtil.java

  17 
vote

public static int restoreBackup(Context context){
  XmlPullParser parser=Xml.newPullParser();
  FileInputStream file=null;
  int appsRestored=0;
  try {
    file=new FileInputStream(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/subackup.xml"));
    parser.setInput(file,"UTF-8");
    int eventType=parser.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
        if (parser.getName().equalsIgnoreCase("apps")) {
          parser.next();
          appsRestored=restoreApps(context,parser);
        }
 else         if (parser.getName().equalsIgnoreCase("prefs")) {
          parser.next();
          restorePrefs(context,parser);
        }
      break;
  }
  eventType=parser.next();
}
}
 catch (XmlPullParserException e) {
Log.e(TAG,"Error restoring backup",e);
return -1;
}
catch (IOException e) {
Log.e(TAG,"Error restoring backup",e);
return -1;
}
return appsRestored;
}
 

Example 54

From project androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/.

Source file: LogHelper.java

  17 
vote

/** 
 * Gets an input on a configuration file placed on the the SDCard.
 * @param fileName the file name
 * @return the input stream to read the file or <code>null</code> if thefile does not exist.
 */
protected static InputStream getConfigurationFileFromSDCard(String fileName){
  File sdcard=Environment.getExternalStorageDirectory();
  if (sdcard == null || !sdcard.exists() || !sdcard.canRead()) {
    return null;
  }
  String sdCardPath=sdcard.getAbsolutePath();
  File propFile=new File(sdCardPath + "/" + fileName);
  if (!propFile.exists()) {
    return null;
  }
  FileInputStream fileIs=null;
  try {
    fileIs=new FileInputStream(propFile);
  }
 catch (  FileNotFoundException e) {
    return null;
  }
  return fileIs;
}
 

Example 55

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: ErrorReporter.java

  17 
vote

private void sendErrorReport() throws IOException {
  ArrayList<String> files=getErrorFiles();
  StringBuilder report=new StringBuilder();
  int count=1;
  for (  String filename : files) {
    try {
      report.append(String.format("--> BEGIN REPORT %d <--\n",count));
      FileInputStream fi=openFileInput(filename);
      if (fi == null) {
        continue;
      }
      int ch;
      while ((ch=fi.read()) != -1) {
        report.append((char)ch);
      }
      fi.close();
      report.append(String.format("--> END REPORT %d <--",count++));
    }
 catch (    Exception ex) {
      Log.e(AnkiDroidApp.TAG,ex.toString());
    }
  }
  sendEmail(report.toString());
}
 

Example 56

From project action-core, under directory /src/test/java/com/ning/metrics/action/hdfs/writer/.

Source file: TestHdfsWriter.java

  16 
vote

@Test(groups="fast") public void testWrite() throws Exception {
  final HdfsWriter writer=new HdfsWriter(fileSystemAccess);
  final String outputFile=outputPath + "/lorem.txt";
  final URI outputURI=writer.write(new FileInputStream(file),outputFile,false,(short)1,1024,"ugo=r");
  final FileStatus status=fileSystemAccess.get().getFileStatus(new Path(outputURI));
  Assert.assertEquals(status.getPath().toString(),"file:" + outputFile);
  Assert.assertEquals(status.getReplication(),(short)1);
  try {
    writer.write(new FileInputStream(file),outputFile,false,(short)1,1024,"ugo=r");
    Assert.fail();
  }
 catch (  IOException e) {
    Assert.assertEquals(e.getLocalizedMessage(),String.format("File already exists:%s",outputFile));
  }
}
 

Example 57

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.

Source file: ViewTools.java

  16 
vote

public String getCommitUrl() throws IOException, CantDoThatException {
  String commitFileName=this.request.getSession().getServletContext().getRealPath("/lastcommit.txt");
  File commitFile=new File(commitFileName);
  try {
    InputStream inputStream=new FileInputStream(commitFileName);
    BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream,Charset.forName("UTF-8")));
    String commitLine=reader.readLine();
    String commitId=commitLine.replace("commit ","");
    inputStream.close();
    return "https://github.com/okohll/agileBase/commit/" + commitId;
  }
 catch (  FileNotFoundException fnfex) {
    logger.error("Commit file " + commitFileName + " not found: "+ fnfex);
    throw new CantDoThatException("Commit log not found");
  }
}
 

Example 58

From project agit, under directory /agit-test-utils/src/main/java/com/madgag/agit/.

Source file: GitTestUtils.java

  16 
vote

public static String gitServerHostAddress() throws IOException, UnknownHostException {
  File hostAddressFile=new File(Environment.getExternalStorageDirectory(),"agit-integration-test.properties");
  Properties properties=new Properties();
  if (hostAddressFile.exists()) {
    properties.load(new FileInputStream(hostAddressFile));
  }
  String[] hostAddresses=properties.getProperty("gitserver.host.address","10.0.2.2").split(",");
  for (  String hostAddress : hostAddresses) {
    if (InetAddress.getByName(hostAddress).isReachable(1000)) {
      Log.d(TAG,"Using git server host : " + hostAddress);
      return hostAddress;
    }
  }
  throw new RuntimeException("No reachable addresses in " + asList(hostAddresses));
}
 

Example 59

From project alphaportal_dev, under directory /sys-src/alphaportal_RESTClient/src/alpha/client/.

Source file: RESTClient.java

  16 
vote

/** 
 * reads the file and transforms it in a payload
 * @param path path of the file
 * @param name name as which the payload should be saved
 * @return a payload
 */
private static Payload readFile(String path,Payload payload){
  InputStream inputStream=null;
  try {
    inputStream=new FileInputStream(path);
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
  ByteArrayOutputStream byteBuffer=new ByteArrayOutputStream();
  byte[] buffer=new byte[BUFFER_SIZE];
  int readBytes=0;
  try {
    while (true) {
      readBytes=inputStream.read(buffer);
      if (readBytes > 0) {
        byteBuffer.write(buffer,0,readBytes);
      }
 else {
        break;
      }
    }
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  payload.setContent(byteBuffer.toByteArray());
  return payload;
}
 

Example 60

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/entity/.

Source file: FileEntity.java

  16 
vote

public void writeTo(final OutputStream outstream) throws IOException {
  if (outstream == null) {
    throw new IllegalArgumentException("Output stream may not be null");
  }
  InputStream instream=new FileInputStream(this.file);
  try {
    byte[] tmp=new byte[4096];
    int l;
    while ((l=instream.read(tmp)) != -1) {
      outstream.write(tmp,0,l);
    }
    outstream.flush();
  }
  finally {
    instream.close();
  }
}
 

Example 61

From project Android-Terminal-Emulator, under directory /src/jackpal/androidterm/.

Source file: ShellTermSession.java

  16 
vote

private void initializeSession(){
  TermSettings settings=mSettings;
  int[] processId=new int[1];
  String path=System.getenv("PATH");
  if (settings.doPathExtensions()) {
    String appendPath=settings.getAppendPath();
    if (appendPath != null && appendPath.length() > 0) {
      path=path + ":" + appendPath;
    }
    if (settings.allowPathPrepend()) {
      String prependPath=settings.getPrependPath();
      if (prependPath != null && prependPath.length() > 0) {
        path=prependPath + ":" + path;
      }
    }
  }
  if (settings.verifyPath()) {
    path=checkPath(path);
  }
  String[] env=new String[2];
  env[0]="TERM=" + settings.getTermType();
  env[1]="PATH=" + path;
  createSubprocess(processId,settings.getShell(),env);
  mProcId=processId[0];
  setTermOut(new FileOutputStream(mTermFd));
  setTermIn(new FileInputStream(mTermFd));
}
 

Example 62

From project android-vpn-settings, under directory /src/com/android/settings/vpn/.

Source file: Util.java

  16 
vote

static boolean copyFiles(File sourceLocation,File targetLocation) throws IOException {
  if (sourceLocation.equals(targetLocation))   return false;
  if (sourceLocation.isDirectory()) {
    if (!targetLocation.exists()) {
      targetLocation.mkdir();
    }
    String[] children=sourceLocation.list();
    for (int i=0; i < children.length; i++) {
      copyFiles(new File(sourceLocation,children[i]),new File(targetLocation,children[i]));
    }
  }
 else   if (sourceLocation.exists()) {
    InputStream in=new FileInputStream(sourceLocation);
    OutputStream out=new FileOutputStream(targetLocation);
    byte[] buf=new byte[1024];
    int len;
    while ((len=in.read(buf)) > 0) {
      out.write(buf,0,len);
    }
    in.close();
    out.close();
  }
  return true;
}
 

Example 63

From project androidannotations, under directory /AndroidAnnotations/androidannotations/src/main/java/com/googlecode/androidannotations/helper/.

Source file: AndroidManifestFinder.java

  16 
vote

private AndroidManifest extractAndroidManifestThrowing() throws Exception {
  File androidManifestFile=findManifestFileThrowing();
  String projectDirectory=androidManifestFile.getParent();
  File projectProperties=new File(projectDirectory,"project.properties");
  boolean libraryProject=false;
  if (projectProperties.exists()) {
    Properties properties=new Properties();
    properties.load(new FileInputStream(projectProperties));
    if (properties.containsKey("android.library")) {
      String androidLibraryProperty=properties.getProperty("android.library");
      libraryProject=androidLibraryProperty.equals("true");
      Messager messager=processingEnv.getMessager();
      messager.printMessage(Kind.NOTE,"Found android.library property in project.properties, value: " + libraryProject);
    }
  }
  return parseThrowing(androidManifestFile,libraryProject);
}
 

Example 64

From project AndroidDevWeekendDub-BookLibrary, under directory /src/org/curiouscreature/android/shelves/util/.

Source file: ImageUtilities.java

  16 
vote

private static Bitmap loadCover(String id){
  final File file=new File(ImportUtilities.getCacheDirectory(),id);
  if (file.exists()) {
    InputStream stream=null;
    try {
      stream=new FileInputStream(file);
      return BitmapFactory.decodeStream(stream,null,null);
    }
 catch (    FileNotFoundException e) {
    }
 finally {
      IOUtilities.closeStream(stream);
    }
  }
  return null;
}
 

Example 65

From project androidpn, under directory /androidpn-server-bin-tomcat/src/org/androidpn/server/xmpp/ssl/.

Source file: SSLKeyManagerFactory.java

  16 
vote

public static KeyManager[] getKeyManagers(String storeType,String keystore,String keypass) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
  KeyManager[] keyManagers;
  if (keystore == null) {
    keyManagers=null;
  }
 else {
    if (keypass == null) {
      keypass="";
    }
    KeyStore keyStore=KeyStore.getInstance(storeType);
    keyStore.load(new FileInputStream(keystore),keypass.toCharArray());
    KeyManagerFactory keyFactory=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyFactory.init(keyStore,keypass.toCharArray());
    keyManagers=keyFactory.getKeyManagers();
  }
  return keyManagers;
}
 

Example 66

From project 4308Cirrus, under directory /tendril-android-lib/src/test/java/edu/colorado/cs/cirrus/android/.

Source file: DeserializationTest.java

  15 
vote

@Test public void canDeserializeMeterReading(){
  RestTemplate restTemplate=new RestTemplate();
  restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(HttpUtils.getNewHttpClient()));
  HttpInputMessage him=new HttpInputMessage(){
    public HttpHeaders getHeaders(){
      return new HttpHeaders();
    }
    public InputStream getBody() throws IOException {
      return new FileInputStream(new File("src/test/resources/MeterReadings.xml"));
    }
  }
;
  for (  HttpMessageConverter<?> hmc : restTemplate.getMessageConverters()) {
    System.out.println("hmc: " + hmc);
    if (hmc.canRead(MeterReadings.class,MediaType.APPLICATION_XML)) {
      HttpMessageConverter<MeterReadings> typedHmc=(HttpMessageConverter<MeterReadings>)hmc;
      System.out.println("Can Read: " + hmc);
      hmc.canRead(MeterReadings.class,MediaType.APPLICATION_XML);
      try {
        MeterReadings mr=(MeterReadings)typedHmc.read(MeterReadings.class,him);
        System.out.println(mr);
      }
 catch (      HttpMessageNotReadableException e) {
        e.printStackTrace();
        fail();
      }
catch (      IOException e) {
        e.printStackTrace();
        fail();
      }
    }
  }
}
 

Example 67

From project akela, under directory /src/test/java/com/mozilla/pig/eval/json/.

Source file: JsonMapTest.java

  15 
vote

private String readFile(String file) throws IOException {
  StringBuilder sb=new StringBuilder();
  BufferedReader reader=null;
  try {
    reader=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
    String line=null;
    while ((line=reader.readLine()) != null) {
      sb.append(line);
    }
  }
  finally {
    if (reader != null) {
      reader.close();
    }
  }
  return sb.toString();
}
 

Example 68

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/mysql/parser/sql/.

Source file: MysqlParser.java

  15 
vote

/** 
 * main method to test parser
 */
public static void main(String args[]) throws com.meidusa.amoeba.parser.ParseException {
  MysqlParser p=null;
  if (args.length < 1) {
    System.out.println("Reading from stdin");
    p=new MysqlParser(System.in);
  }
 else {
    try {
      p=new MysqlParser(new DataInputStream(new FileInputStream(args[0])));
    }
 catch (    FileNotFoundException e) {
      System.out.println("File " + args[0] + " not found. Reading from stdin");
      p=new MysqlParser(System.in);
    }
  }
  if (args.length > 0) {
    System.out.println(args[0]);
  }
  Statment statment=p.doParse();
  System.out.println(statment.getExpression());
}
 

Example 69

From project Android-File-Manager, under directory /src/com/nexes/manager/.

Source file: ApplicationBackup.java

  15 
vote

public void run(){
  BufferedInputStream mBuffIn;
  BufferedOutputStream mBuffOut;
  Message msg;
  int len=mDataSource.size();
  int read=0;
  for (int i=0; i < len; i++) {
    ApplicationInfo info=mDataSource.get(i);
    String source_dir=info.sourceDir;
    String out_file=source_dir.substring(source_dir.lastIndexOf("/") + 1,source_dir.length());
    try {
      mBuffIn=new BufferedInputStream(new FileInputStream(source_dir));
      mBuffOut=new BufferedOutputStream(new FileOutputStream(BACKUP_LOC + out_file));
      while ((read=mBuffIn.read(mData,0,BUFFER)) != -1)       mBuffOut.write(mData,0,read);
      mBuffOut.flush();
      mBuffIn.close();
      mBuffOut.close();
      msg=new Message();
      msg.what=SET_PROGRESS;
      msg.obj=i + " out of " + len+ " apps backed up";
      mHandler.sendMessage(msg);
    }
 catch (    FileNotFoundException e) {
      e.printStackTrace();
    }
catch (    IOException e) {
      e.printStackTrace();
    }
  }
  mHandler.sendEmptyMessage(FINISH_PROGRESS);
}
 

Example 70

From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/.

Source file: OcrInitAsyncTask.java

  15 
vote

/** 
 * Unzips the given Gzipped file to the given destination, and deletes the gzipped file.
 * @param zippedFile The gzipped file to be uncompressed
 * @param outFilePath File to unzip to, including path
 * @throws FileNotFoundException
 * @throws IOException
 */
private void gunzip(File zippedFile,File outFilePath) throws FileNotFoundException, IOException {
  int uncompressedFileSize=getGzipSizeUncompressed(zippedFile);
  Integer percentComplete;
  int percentCompleteLast=0;
  int unzippedBytes=0;
  final Integer progressMin=0;
  int progressMax=100 - progressMin;
  publishProgress("Uncompressing data for " + languageName + "...",progressMin.toString());
  String extension=zippedFile.toString().substring(zippedFile.toString().length() - 16);
  if (extension.equals(".tar.gz.download")) {
    progressMax=50;
  }
  GZIPInputStream gzipInputStream=new GZIPInputStream(new BufferedInputStream(new FileInputStream(zippedFile)));
  OutputStream outputStream=new FileOutputStream(outFilePath);
  BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(outputStream);
  final int BUFFER=8192;
  byte[] data=new byte[BUFFER];
  int len;
  while ((len=gzipInputStream.read(data,0,BUFFER)) > 0) {
    bufferedOutputStream.write(data,0,len);
    unzippedBytes+=len;
    percentComplete=(int)((unzippedBytes / (float)uncompressedFileSize) * progressMax) + progressMin;
    if (percentComplete > percentCompleteLast) {
      publishProgress("Uncompressing data for " + languageName + "...",percentComplete.toString());
      percentCompleteLast=percentComplete;
    }
  }
  gzipInputStream.close();
  bufferedOutputStream.flush();
  bufferedOutputStream.close();
  if (zippedFile.exists()) {
    zippedFile.delete();
  }
}
 

Example 71

From project android-vpn-server, under directory /src/com/android/server/vpn/.

Source file: VpnServiceBinder.java

  15 
vote

private void checkSavedStates(){
  try {
    ObjectInputStream ois=new ObjectInputStream(new FileInputStream(getStateFilePath()));
    mService=(VpnService<? extends VpnProfile>)ois.readObject();
    mService.recover(this);
    ois.close();
  }
 catch (  FileNotFoundException e) {
  }
catch (  Throwable e) {
    Log.i("VpnServiceBinder","recovery error, remove states: " + e);
    removeStates();
  }
}
 

Example 72

From project android_packages_apps_Exchange, under directory /src/com/android/exchange/.

Source file: EasOutboxService.java

  15 
vote

public SendMailEntity(Context context,FileInputStream instream,long length,int tag,Message message){
  super(instream,length);
  mContext=context;
  mFileStream=instream;
  mFileLength=length;
  mSendTag=tag;
  mMessage=message;
}