Java Code Examples for java.io.FileNotFoundException

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 android_packages_apps_FileManager, under directory /src/org/openintents/filemanager/.

Source file: FileManagerProvider.java

  35 
vote

@Override public ParcelFileDescriptor openFile(Uri uri,String mode) throws FileNotFoundException {
  if (uri.toString().startsWith(FILE_PROVIDER_PREFIX)) {
    int m=ParcelFileDescriptor.MODE_READ_ONLY;
    if (mode.equalsIgnoreCase("rw"))     m=ParcelFileDescriptor.MODE_READ_WRITE;
    File f=new File(uri.getPath());
    ParcelFileDescriptor pfd=ParcelFileDescriptor.open(f,m);
    return pfd;
  }
 else {
    throw new FileNotFoundException("Unsupported uri: " + uri.toString());
  }
}
 

Example 2

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

Source file: FilePartSource.java

  33 
vote

/** 
 * Constructor for FilePartSource.
 * @param file the FilePart source File. 
 * @throws FileNotFoundException if the file does not exist or cannot be read
 */
public FilePartSource(File file) throws FileNotFoundException {
  this.file=file;
  if (file != null) {
    if (!file.isFile()) {
      throw new FileNotFoundException("File is not a normal file.");
    }
    if (!file.canRead()) {
      throw new FileNotFoundException("File is not readable.");
    }
    this.fileName=file.getName();
  }
}
 

Example 3

From project Aardvark, under directory /aardvark/src/main/test/gw/vark/it/.

Source file: ITUtil.java

  32 
vote

public static File findFile(File dir,final String pattern) throws FileNotFoundException {
  if (!dir.exists()) {
    throw new IllegalArgumentException(dir + " does not exist");
  }
  if (!dir.isDirectory()) {
    throw new IllegalArgumentException(dir + " is not a directory");
  }
  File[] found=dir.listFiles(new FilenameFilter(){
    @Override public boolean accept(    File dir,    String name){
      return name.matches(pattern);
    }
  }
);
  if (found.length == 0) {
    throw new FileNotFoundException("file matching pattern \"" + pattern + "\" not found in directory "+ dir);
  }
  if (found.length > 1) {
    throw new FileNotFoundException("multiple files found matching pattern \"" + pattern + "\" in directory "+ dir);
  }
  return found[0];
}
 

Example 4

From project ActionBarSherlock, under directory /library/src/com/actionbarsherlock/widget/.

Source file: SuggestionsAdapter.java

  32 
vote

/** 
 * Gets a drawable by URI, without using the cache.
 * @return A drawable, or {@code null} if the drawable could not be loaded.
 */
private Drawable getDrawable(Uri uri){
  try {
    String scheme=uri.getScheme();
    if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
      try {
        return getTheDrawable(uri);
      }
 catch (      Resources.NotFoundException ex) {
        throw new FileNotFoundException("Resource does not exist: " + uri);
      }
    }
 else {
      InputStream stream=mProviderContext.getContentResolver().openInputStream(uri);
      if (stream == null) {
        throw new FileNotFoundException("Failed to open " + uri);
      }
      try {
        return Drawable.createFromStream(stream,null);
      }
  finally {
        try {
          stream.close();
        }
 catch (        IOException ex) {
          Log.e(LOG_TAG,"Error closing icon stream for " + uri,ex);
        }
      }
    }
  }
 catch (  FileNotFoundException fnfe) {
    Log.w(LOG_TAG,"Icon not found: " + uri + ", "+ fnfe.getMessage());
    return null;
  }
}
 

Example 5

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

Source file: FinalizableReferenceQueue.java

  32 
vote

/** 
 * Gets URL for base of path containing Finalizer.class.
 */
URL getBaseUrl() throws IOException {
  String finalizerPath=FINALIZER_CLASS_NAME.replace('.','/') + ".class";
  URL finalizerUrl=getClass().getClassLoader().getResource(finalizerPath);
  if (finalizerUrl == null) {
    throw new FileNotFoundException(finalizerPath);
  }
  String urlString=finalizerUrl.toString();
  if (!urlString.endsWith(finalizerPath)) {
    throw new IOException("Unsupported path style: " + urlString);
  }
  urlString=urlString.substring(0,urlString.length() - finalizerPath.length());
  return new URL(finalizerUrl,urlString);
}
 

Example 6

From project annotare2, under directory /app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/.

Source file: UploadedFiles.java

  32 
vote

public static FileItem getOne(HttpSession session) throws FileNotFoundException {
  ArrayList<FileItem> items=(ArrayList<FileItem>)session.getAttribute(GWTUPLOAD_ATTRIBUTE_NAME);
  if (items.isEmpty()) {
    throw new FileNotFoundException("Can't find the uploaded file.");
  }
  return items.get(0);
}
 

Example 7

From project apb, under directory /modules/apb-base/src/apb/.

Source file: ProjectBuilder.java

  32 
vote

@NotNull private File searchInProjectPath(String projectElement) throws FileNotFoundException {
  for (  File dir : projectPath) {
    File file=new File(dir,projectElement);
    if (file.exists()) {
      return file;
    }
  }
  throw new FileNotFoundException(projectElement);
}
 

Example 8

From project aether-core, under directory /aether-connector-file/src/main/java/org/eclipse/aether/connector/file/.

Source file: FileRepositoryWorker.java

  31 
vote

private long copy(File src,File target) throws TransferCancelledException, IOException {
  if (src == null) {
    throw new IllegalArgumentException("source file not specified");
  }
  if (!src.isFile()) {
    throw new FileNotFoundException(src.getAbsolutePath());
  }
  if (target == null) {
    throw new IllegalArgumentException("target file not specified");
  }
  resource.setContentLength(src.length());
  TransferEvent.Builder event=newEvent(transfer);
  catapult.fireStarted(event);
  return fileProcessor.copy(src,target,new FileProcessor.ProgressListener(){
    int total=0;
    public void progressed(    ByteBuffer buffer) throws IOException {
      total+=buffer.remaining();
      TransferEvent.Builder event=newEvent(transfer);
      event.setDataBuffer(buffer).setTransferredBytes(total);
      try {
        catapult.fireProgressed(event);
      }
 catch (      TransferCancelledException e) {
        throw new IOException("Transfer was cancelled: " + e.getMessage());
      }
    }
  }
);
}
 

Example 9

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

Source file: ReporterPropertiesReader.java

  31 
vote

/** 
 * Instantiates a new reporter properties reader.
 */
public ReporterPropertiesReader(){
  properties=new Properties();
  try {
    InputStream in=getClass().getClassLoader().getResourceAsStream(configFilePath);
    if (in != null) {
      properties.load(in);
      isLoaded=true;
    }
 else     throw new FileNotFoundException("Can't find reporter.properties file");
  }
 catch (  IOException e) {
    logger.error(e.getMessage());
  }
}
 

Example 10

From project android-database-sqlcipher, under directory /src/net/sqlcipher/.

Source file: DatabaseUtils.java

  31 
vote

public static void readExceptionWithFileNotFoundExceptionFromParcel(Parcel reply) throws FileNotFoundException {
  int code=reply.readInt();
  if (code == 0)   return;
  String msg=reply.readString();
  if (code == 1) {
    throw new FileNotFoundException(msg);
  }
 else {
    DatabaseUtils.readExceptionFromParcel(reply,msg,code);
  }
}
 

Example 11

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

Source file: XmlMerger.java

  30 
vote

/** 
 * This method creates a result document if it is missing, or updates existing one if the source file has modification.<br /> If there are no changes - nothing happens.
 * @throws FileNotFoundException when source file doesn't exists.
 * @throws XMLStreamException    when XML processing error was occurred.
 */
public void process() throws Exception {
  logger.debug("Processing " + sourceFile + " files into "+ destFile);
  if (!sourceFile.exists())   throw new FileNotFoundException("Source file " + sourceFile.getPath() + " not found.");
  boolean needUpdate=false;
  if (!destFile.exists()) {
    logger.debug("Dest file not found - creating new file");
    needUpdate=true;
  }
 else   if (!metaDataFile.exists()) {
    logger.debug("Meta file not found - creating new file");
    needUpdate=true;
  }
 else {
    logger.debug("Dest file found - checking file modifications");
    needUpdate=checkFileModifications();
  }
  if (needUpdate) {
    logger.debug("Modifications found. Updating...");
    try {
      doUpdate();
    }
 catch (    Exception e) {
      FileUtils.deleteQuietly(destFile);
      FileUtils.deleteQuietly(metaDataFile);
      throw e;
    }
  }
 else {
    logger.debug("Files are up-to-date");
  }
}
 

Example 12

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

Source file: FileUtils.java

  30 
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 13

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/entities/.

Source file: PictoView.java

  30 
vote

/** 
 * Method to link a photo to this arrow, giving the photo position on arrow layout
 * @param picture
 * @param x
 * @param y
 * @throws FileNotFoundException
 */
public Bitmap setSupport(Bitmap picture,float targetx,float targety,Context c) throws FileNotFoundException {
  Bitmap arrow=((BitmapDrawable)this.getDrawable()).getBitmap();
  float coeffx=targetx / getWidth();
  float coeffy=targety / getHeight();
  int scaledOffsetX=(int)(offsetx * coeffx);
  int scaledOffsetY=(int)(offsety * coeffy);
  Matrix matrix=new Matrix();
  matrix.postRotate(degree,(arrow.getWidth() / 2),(arrow.getHeight() / 2));
  arrow=Bitmap.createBitmap(arrow,0,0,arrow.getWidth(),arrow.getHeight(),matrix,true);
  Bitmap b=picture.copy(picture.getConfig(),true);
  Canvas myCanvas=new Canvas(b);
  myCanvas.drawBitmap(arrow,(b.getWidth() - arrow.getWidth()) / 2 + scaledOffsetX,(b.getHeight() - arrow.getHeight()) / 2 + scaledOffsetY,new Paint());
  b.compress(CompressFormat.JPEG,80,c.openFileOutput("arrowed.jpg",Context.MODE_PRIVATE));
  return b;
}
 

Example 14

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

Source file: ShellTermSession.java

  30 
vote

private void createSubprocess(int[] processId,String shell,String[] env){
  ArrayList<String> argList=parse(shell);
  String arg0;
  String[] args;
  try {
    arg0=argList.get(0);
    File file=new File(arg0);
    if (!file.exists()) {
      Log.e(TermDebug.LOG_TAG,"Shell " + arg0 + " not found!");
      throw new FileNotFoundException(arg0);
    }
 else     if (!FileCompat.canExecute(file)) {
      Log.e(TermDebug.LOG_TAG,"Shell " + arg0 + " not executable!");
      throw new FileNotFoundException(arg0);
    }
    args=argList.toArray(new String[1]);
  }
 catch (  Exception e) {
    argList=parse(mSettings.getFailsafeShell());
    arg0=argList.get(0);
    args=argList.toArray(new String[1]);
  }
  mTermFd=Exec.createSubprocess(arg0,args,env,processId);
}
 

Example 15

From project androidpn, under directory /androidpn-server-src/server/src/main/java/org/androidpn/server/xmpp/.

Source file: XmppServer.java

  30 
vote

private void locateServer() throws FileNotFoundException {
  String baseDir=System.getProperty("base.dir","..");
  log.debug("base.dir=" + baseDir);
  if (serverHomeDir == null) {
    try {
      File confDir=new File(baseDir,"conf");
      if (confDir.exists()) {
        serverHomeDir=confDir.getParentFile().getCanonicalPath();
      }
    }
 catch (    FileNotFoundException fe) {
    }
catch (    IOException ie) {
    }
  }
  if (serverHomeDir == null) {
    System.err.println("Could not locate home.");
    throw new FileNotFoundException();
  }
 else {
    Config.setProperty("server.home.dir",serverHomeDir);
    log.debug("server.home.dir=" + serverHomeDir);
  }
}
 

Example 16

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

Source file: GalleryProvider.java

  30 
vote

@Override public ParcelFileDescriptor openFile(Uri uri,String mode) throws FileNotFoundException {
  long token=Binder.clearCallingIdentity();
  try {
    if (mode.contains("w")) {
      throw new FileNotFoundException("cannot open file for write");
    }
    Path path=Path.fromString(uri.getPath());
    MediaObject object=mDataManager.getMediaObject(path);
    if (object == null) {
      throw new FileNotFoundException(uri.toString());
    }
    if (PicasaSource.isPicasaImage(object)) {
      return PicasaSource.openFile(getContext(),object,mode);
    }
 else     if (object instanceof MtpImage) {
      return openPipeHelper(uri,null,null,null,new MtpPipeDataWriter((MtpImage)object));
    }
 else {
      throw new FileNotFoundException("unspported type: " + object);
    }
  }
  finally {
    Binder.restoreCallingIdentity(token);
  }
}
 

Example 17

From project android_packages_apps_QuickSearchBox, under directory /src/com/android/quicksearchbox/.

Source file: PackageIconLoader.java

  30 
vote

/** 
 * Gets a drawable by URI.
 * @return A drawable, or {@code null} if the drawable could not be loaded.
 */
private Drawable getDrawable(Uri uri){
  try {
    String scheme=uri.getScheme();
    if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
      OpenResourceIdResult r=getResourceId(uri);
      try {
        return r.r.getDrawable(r.id);
      }
 catch (      Resources.NotFoundException ex) {
        throw new FileNotFoundException("Resource does not exist: " + uri);
      }
    }
 else {
      InputStream stream=mPackageContext.getContentResolver().openInputStream(uri);
      if (stream == null) {
        throw new FileNotFoundException("Failed to open " + uri);
      }
      try {
        return Drawable.createFromStream(stream,null);
      }
  finally {
        try {
          stream.close();
        }
 catch (        IOException ex) {
          Log.e(TAG,"Error closing icon stream for " + uri,ex);
        }
      }
    }
  }
 catch (  FileNotFoundException fnfe) {
    Log.w(TAG,"Icon not found: " + uri + ", "+ fnfe.getMessage());
    return null;
  }
}
 

Example 18

From project android_packages_apps_Tag, under directory /src/com/android/apps/tag/provider/.

Source file: TagProvider.java

  30 
vote

/** 
 * A helper function for implementing  {@link #openFile}, for creating a data pipe and background thread allowing you to stream generated data back to the client.  This function returns a new ParcelFileDescriptor that should be returned to the caller (the caller is responsible for closing it).
 * @param uri The URI whose data is to be written.
 * @param func Interface implementing the function that will actuallystream the data.
 * @return Returns a new ParcelFileDescriptor holding the read side ofthe pipe.  This should be returned to the caller for reading; the caller is responsible for closing it when done.
 */
public ParcelFileDescriptor openMimePipe(final Uri uri,final TagProviderPipeDataWriter func) throws FileNotFoundException {
  try {
    final ParcelFileDescriptor[] fds=ParcelFileDescriptor.createPipe();
    AsyncTask<Object,Object,Object> task=new AsyncTask<Object,Object,Object>(){
      @Override protected Object doInBackground(      Object... params){
        func.writeMimeDataToPipe(fds[1],uri);
        try {
          fds[1].close();
        }
 catch (        IOException e) {
          Log.w(TAG,"Failure closing pipe",e);
        }
        return null;
      }
    }
;
    task.execute((Object[])null);
    return fds[0];
  }
 catch (  IOException e) {
    throw new FileNotFoundException("failure making pipe");
  }
}
 

Example 19

From project abalone-android, under directory /src/com/bytopia/abalone/.

Source file: GameActivity.java

  29 
vote

@Override protected void onPause(){
  Log.d("state","paused");
  try {
    FileOutputStream fos=openFileOutput(FILE_NAME,Context.MODE_PRIVATE);
    ObjectOutputStream oos=new ObjectOutputStream(fos);
    oos.writeObject(game.getBoard());
    oos.writeByte(game.getSide());
    oos.writeByte(game.getVsType());
    if (cpuType != null) {
      oos.writeObject(cpuType);
    }
    oos.writeByte((byte)game.getBoard().getMarblesCaptured(Side.BLACK));
    oos.writeByte((byte)game.getBoard().getMarblesCaptured(Side.WHITE));
    oos.close();
  }
 catch (  FileNotFoundException e) {
    Log.d("state","FileNotFound");
  }
catch (  IOException e) {
    Log.d("state","IO Exception");
  }
  super.onPause();
}
 

Example 20

From project addis, under directory /application/src/integration-test/java/org/drugis/addis/util/JSMAAintegration/.

Source file: NetworkBenefitRiskIT.java

  29 
vote

@Test public void testNetworkBRRelativeEffects() throws FileNotFoundException, IOException, InterruptedException {
  List<Alternative> alternatives=new ArrayList<Alternative>(d_model.getAlternatives());
  alternatives=movePlacebo(alternatives,findPlacebo(alternatives),0);
  verifyRelativeEffects(d_brpm,d_model,"HAM-D Responders",buildHAMD(alternatives));
  verifyRelativeEffects(d_brpm,d_model,"Diarrhea",buildDiarrhea(alternatives));
  verifyRelativeEffects(d_brpm,d_model,"Dizziness",buildDizziness(alternatives));
  verifyRelativeEffects(d_brpm,d_model,"Headache",buildHeadache(alternatives));
  verifyRelativeEffects(d_brpm,d_model,"Insomnia",buildInsomnia(alternatives));
  verifyRelativeEffects(d_brpm,d_model,"Nausea",buildNausea(alternatives));
}
 

Example 21

From project AdminCmd, under directory /src/main/java/be/Balor/Manager/.

Source file: LocaleManager.java

  29 
vote

/** 
 * Reload the locale file
 */
public void reload(){
  try {
    for (    final ExtendedConfiguration exConf : localesFiles.values()) {
      exConf.reload();
    }
  }
 catch (  final FileNotFoundException e) {
    ACLogger.severe("Locale Reload Problem :",e);
  }
catch (  final IOException e) {
    ACLogger.severe("Locale Reload Problem :",e);
  }
catch (  final InvalidConfigurationException e) {
    ACLogger.severe("Locale Reload Problem :",e);
  }
}
 

Example 22

From project AdServing, under directory /modules/utilities/utils/src/main/java/net/mad/ads/base/utils/utils/logging/.

Source file: LogWrapper.java

  29 
vote

public void init(Class clazz,File logPropertiesFile){
  try {
    Properties prop=Properties2.loadProperties(logPropertiesFile);
    if (logger == null) {
      logger=Logger.getLogger(prop.getProperty(LOGGER_NAME));
      String fileName=prop.getProperty(LOG_FILE_NAME);
      RollingFileHandler rfh=new RollingFileHandler(fileName,".log");
      rfh.setFormatter(new CustomMessageFormatter(new MessageFormat(prop.getProperty(MESSAGE_FORMAT))));
      logger.setLevel(AdLevel.parse(prop.getProperty(LOG_LEVEL)));
      logger.addHandler(rfh);
    }
    this.className=clazz.getName();
  }
 catch (  FileNotFoundException fnfe) {
    fnfe.printStackTrace();
  }
catch (  IOException ioe) {
    ioe.printStackTrace();
  }
}
 

Example 23

From project aether-ant, under directory /src/main/java/org/eclipse/aether/ant/listeners/.

Source file: AntRepositoryListener.java

  29 
vote

@Override public void metadataInvalid(RepositoryEvent event){
  Exception exception=event.getException();
  StringBuilder buffer=new StringBuilder(256);
  buffer.append("The metadata ");
  if (event.getMetadata().getFile() != null) {
    buffer.append(event.getMetadata().getFile());
  }
 else {
    buffer.append(event.getMetadata());
  }
  if (exception instanceof FileNotFoundException) {
    buffer.append(" is inaccessible");
  }
 else {
    buffer.append(" is invalid");
  }
  if (exception != null) {
    buffer.append(": ");
    buffer.append(exception.getMessage());
  }
  task.log(buffer.toString(),exception,Project.MSG_WARN);
}
 

Example 24

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

Source file: ViewTools.java

  29 
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 25

From project agorava-core, under directory /agorava-core-impl-cdi/src/test/java/org/agorava/core/cdi/.

Source file: BadOAuthServiceImplTest.java

  29 
vote

@Deployment(testable=false) public static Archive<?> createTestArchive() throws FileNotFoundException {
  WebArchive ret=ShrinkWrap.create(WebArchive.class,"test.war").addPackages(true,"org.agorava").addAsLibraries(new File("../agorava-core-api/target/agorava-core-api.jar"));
  System.out.println(System.getProperty("arquillian"));
  if (("weld-ee-embedded-1.1".equals(System.getProperty("arquillian")) || System.getProperty("arquillian") == null)) {
  }
 else {
    ret.addAsLibraries(DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("pom.xml").artifact("org.scribe:scribe").artifact("org.apache.commons:commons-lang3").artifact("org.codehaus.jackson:jackson-mapper-asl").artifact("com.google.guava:guava").resolveAsFiles());
  }
  return ret;
}
 

Example 26

From project agorava-twitter, under directory /agorava-twitter-cdi/src/test/java/org/agorava/twitter/cdi/test/.

Source file: TwitterTest.java

  29 
vote

@Deployment public static Archive<?> createTestArchive() throws FileNotFoundException {
  WebArchive ret=ShrinkWrap.create(WebArchive.class,"test.war").addPackages(true,"org.agorava").addClass(TwitterServiceProducer.class).addAsLibraries(new File("../agorava-twitter-api/target/agorava-twitter-api.jar"));
  System.out.println(System.getProperty("arquillian"));
  if (("weld-ee-embedded-1.1".equals(System.getProperty("arquillian")) || System.getProperty("arquillian") == null)) {
  }
 else {
    ret.addAsLibraries(DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("pom.xml").artifact("org.jboss.solder:solder-impl").artifact("org.scribe:scribe").artifact("org.apache.commons:commons-lang3").artifact("org.codehaus.jackson:jackson-mapper-asl").artifact("com.google.guava:guava").resolveAsFiles());
  }
  return ret;
}
 

Example 27

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

Source file: GameInfo.java

  29 
vote

public void readTerritoryPolyTxt() throws FileNotFoundException, IOException {
  Map<String,List<Polygon>> polys=PointFileReaderWriter.readOneToManyPolygons(getClass().getResourceAsStream("/got/resource/txt/polygons.txt"));
  for (  String name : polys.keySet()) {
    for (    TerritoryInfo ti : getTerrMap().values()) {
      if (ti.getName().equals(name.trim())) {
        ti.setPoly(polys.get(name).get(0));
        break;
      }
    }
  }
}
 

Example 28

From project aim3-tu-berlin, under directory /seminar/exercises/datamining/core/src/test/java/de/tuberlin/dima/aim/exercises/.

Source file: HadoopAndPactTestcase.java

  29 
vote

protected static void writeLines(File file,Iterable<String> lines) throws FileNotFoundException {
  PrintWriter writer=new PrintWriter(new OutputStreamWriter(new FileOutputStream(file),Charset.forName("UTF-8")));
  try {
    for (    String line : lines) {
      writer.println(line);
    }
  }
  finally {
    writer.close();
  }
}
 

Example 29

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

Source file: NoaaService.java

  29 
vote

protected void writeObject(Object object,File objFile){
  try {
    ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(objFile));
    out.writeObject(object);
    out.close();
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 30

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

Source file: WWWBlob.java

  29 
vote

private URLConnection connect(boolean input,boolean cache) throws IOException {
  ensureOpen();
  URLConnection con;
  if ((urlc != null) && input)   con=urlc;
 else {
    con=url.openConnection();
    con.setAllowUserInteraction(false);
    if (input)     con.setDoInput(true);
 else     con.setDoOutput(true);
  }
  if (input) {
    try {
      content=streamManager.manageInputStream(owner,con.getInputStream());
      exists=true;
    }
 catch (    FileNotFoundException fnfe) {
      logger.debug("blob doesn't exist for '" + id + "'",fnfe);
      exists=false;
      size=null;
      urlc=null;
      throw new MissingBlobException(id);
    }
    size=(long)con.getContentLength();
    urlc=cache ? con : null;
  }
  return con;
}
 

Example 31

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

Source file: Store.java

  29 
vote

public T read(){
  FileInputStream in;
  try {
    in=new FileInputStream(this.file);
    ObjectInputStream inStream=new ObjectInputStream(in);
    @SuppressWarnings("unchecked") T result=(T)inStream.readObject();
    inStream.close();
    return result;
  }
 catch (  ClassNotFoundException e) {
    LogEx.exception(e);
    return null;
  }
catch (  FileNotFoundException e1) {
    LogEx.warning("File " + this.file.getName() + " does not exist.");
  }
catch (  IOException e) {
    LogEx.exception(e);
  }
catch (  Exception ex) {
    LogEx.exception(ex);
  }
  return null;
}
 

Example 32

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

Source file: RESTClient.java

  29 
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 33

From project ambrose, under directory /common/src/main/java/azkaban/common/utils/.

Source file: Props.java

  29 
vote

public Props(Props parent,List<String> files) throws FileNotFoundException, IOException {
  this(parent);
  for (int i=0; i < files.size(); i++) {
    InputStream input=new BufferedInputStream(new FileInputStream(new File(files.get(i)).getAbsolutePath()));
    loadFrom(input);
    input.close();
  }
}
 

Example 34

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

Source file: MysqlParser.java

  29 
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 35

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

Source file: FileSource.java

  29 
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 36

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

Source file: StatsCsvReaderWriter.java

  29 
vote

private static boolean isValidFile(String accountName,InputStream in,List<String> packageNames) throws ServiceExceptoin {
  if (packageNames.isEmpty()) {
    return true;
  }
  CSVReader reader=null;
  try {
    reader=new CSVReader(new InputStreamReader(in));
    String[] firstLine=reader.readNext();
    if (firstLine != null) {
      if (HEADER_LIST.length >= firstLine.length) {
        for (int i=0; i < HEADER_LIST.length - 1; i++) {
          if (!HEADER_LIST[i].equals(firstLine[i])) {
            return false;
          }
        }
        String[] secondLine=reader.readNext();
        String packageName=secondLine[0];
        if (secondLine != null) {
          return packageNames.contains(packageName);
        }
      }
    }
  }
 catch (  FileNotFoundException e) {
    throw new ServiceExceptoin(e);
  }
catch (  IOException e) {
    throw new ServiceExceptoin(e);
  }
 finally {
    Utils.closeSilently(reader);
  }
  return false;
}
 

Example 37

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

Source file: SimpleMultipartEntity.java

  29 
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 38

From project android-bankdroid, under directory /src/com/liato/bankdroid/lockpattern/.

Source file: LockPatternUtils.java

  29 
vote

/** 
 * Check to see if a pattern matches the saved pattern.  If no pattern exists, always returns true.
 * @param pattern The pattern to check.
 * @return Whether the pattern matchees the stored one.
 */
public boolean checkPattern(List<LockPatternView.Cell> pattern){
  try {
    RandomAccessFile raf=new RandomAccessFile(sLockPatternFilename,"r");
    final byte[] stored=new byte[(int)raf.length()];
    int got=raf.read(stored,0,stored.length);
    raf.close();
    if (got <= 0) {
      return true;
    }
    return Arrays.equals(stored,LockPatternUtils.patternToHash(pattern));
  }
 catch (  FileNotFoundException fnfe) {
    return true;
  }
catch (  IOException ioe) {
    return true;
  }
}
 

Example 39

From project android-client, under directory /xwiki-android-core/src/org/xwiki/android/data/fileStore/.

Source file: DocumentFaoImpSer.java

  29 
vote

@Override public Document load(File file){
  ObjectInputStream ois;
  Document doc=null;
  try {
    ois=new ObjectInputStream(new FileInputStream(file));
    doc=((Document)ois.readObject());
  }
 catch (  StreamCorruptedException e) {
    e.printStackTrace();
  }
catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
catch (  ClassNotFoundException e) {
    e.printStackTrace();
  }
  return doc;
}
 

Example 40

From project android-cropimage, under directory /src/com/android/camera/gallery/.

Source file: BaseImage.java

  29 
vote

private void setupDimension(){
  ParcelFileDescriptor input=null;
  try {
    input=mContentResolver.openFileDescriptor(mUri,"r");
    BitmapFactory.Options options=new BitmapFactory.Options();
    options.inJustDecodeBounds=true;
    BitmapManager.instance().decodeFileDescriptor(input.getFileDescriptor(),options);
    mWidth=options.outWidth;
    mHeight=options.outHeight;
  }
 catch (  FileNotFoundException ex) {
    mWidth=0;
    mHeight=0;
  }
 finally {
    Util.closeSilently(input);
  }
}
 

Example 41

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

Source file: ApplicationBackup.java

  29 
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 42

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

Source file: FileManager.java

  29 
vote

/** 
 * @param old		the file to be copied
 * @param newDir	the directory to move the file to
 * @return
 */
public int copyToDirectory(String old,String newDir){
  File old_file=new File(old);
  File temp_dir=new File(newDir);
  byte[] data=new byte[BUFFER];
  int read=0;
  if (old_file.isFile() && temp_dir.isDirectory() && temp_dir.canWrite()) {
    String file_name=old.substring(old.lastIndexOf("/"),old.length());
    File cp_file=new File(newDir + file_name);
    try {
      BufferedOutputStream o_stream=new BufferedOutputStream(new FileOutputStream(cp_file));
      BufferedInputStream i_stream=new BufferedInputStream(new FileInputStream(old_file));
      while ((read=i_stream.read(data,0,BUFFER)) != -1)       o_stream.write(data,0,read);
      o_stream.flush();
      i_stream.close();
      o_stream.close();
    }
 catch (    FileNotFoundException e) {
      Log.e("FileNotFoundException",e.getMessage());
      return -1;
    }
catch (    IOException e) {
      Log.e("IOException",e.getMessage());
      return -1;
    }
  }
 else   if (old_file.isDirectory() && temp_dir.isDirectory() && temp_dir.canWrite()) {
    String files[]=old_file.list();
    String dir=newDir + old.substring(old.lastIndexOf("/"),old.length());
    int len=files.length;
    if (!new File(dir).mkdir())     return -1;
    for (int i=0; i < len; i++)     copyToDirectory(old + "/" + files[i],dir);
  }
 else   if (!temp_dir.canWrite())   return -1;
  return 0;
}
 

Example 43

From project android-joedayz, under directory /Proyectos/FBConnectTest/src/com/facebook/android/.

Source file: AsyncFacebookRunner.java

  29 
vote

/** 
 * Invalidate the current user session by removing the access token in memory, clearing the browser cookies, and calling auth.expireSession through the API. The application will be notified when logout is complete via the callback interface. Note that this method is asynchronous and the callback will be invoked in a background thread; operations that affect the UI will need to be posted to the UI thread or an appropriate handler.
 * @param context The Android context in which the logout should be called: it should be the same context in which the login occurred in order to clear any stored cookies
 * @param listener Callback interface to notify the application when the request has completed.
 * @param state An arbitrary object used to identify the request when it returns to the callback. This has no effect on the request itself.
 */
public void logout(final Context context,final RequestListener listener,final Object state){
  new Thread(){
    @Override public void run(){
      try {
        String response=fb.logout(context);
        if (response.length() == 0 || response.equals("false")) {
          listener.onFacebookError(new FacebookError("auth.expireSession failed"),state);
          return;
        }
        listener.onComplete(response,state);
      }
 catch (      FileNotFoundException e) {
        listener.onFileNotFoundException(e,state);
      }
catch (      MalformedURLException e) {
        listener.onMalformedURLException(e,state);
      }
catch (      IOException e) {
        listener.onIOException(e,state);
      }
    }
  }
.start();
}
 

Example 44

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

Source file: TileMemoryCardCache.java

  29 
vote

/** 
 * @param mapGeneratorJob key of the image whose data should be returned.
 * @param buffer the buffer in which the image data should be copied.
 * @return true if the image data were copied successfully, false otherwise.
 * @see Map#get(Object)
 */
boolean get(MapGeneratorJob mapGeneratorJob,ByteBuffer buffer){
  try {
    File inputFile;
synchronized (this) {
      inputFile=this.map.get(mapGeneratorJob);
    }
    FileInputStream fileInputStream=new FileInputStream(inputFile);
    if (fileInputStream.read(buffer.array()) == buffer.array().length) {
      buffer.rewind();
    }
    fileInputStream.close();
    return true;
  }
 catch (  FileNotFoundException e) {
synchronized (this) {
      this.map.remove(mapGeneratorJob);
    }
    return false;
  }
catch (  IOException e) {
    Logger.exception(e);
    return false;
  }
}
 

Example 45

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

Source file: OcrInitAsyncTask.java

  29 
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 46

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

Source file: ContainerObjectDetails.java

  29 
vote

private boolean writeFile(byte[] data){
  String directoryName=Environment.getExternalStorageDirectory().getPath() + DOWNLOAD_DIRECTORY;
  File f=new File(directoryName);
  if (!f.isDirectory()) {
    if (!f.mkdir()) {
      return false;
    }
  }
  String filename=directoryName + "/" + objects.getCName();
  File object=new File(filename);
  BufferedOutputStream bos=null;
  try {
    FileOutputStream fos=new FileOutputStream(object);
    bos=new BufferedOutputStream(fos);
    bos.write(data);
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
 finally {
    if (bos != null) {
      try {
        bos.flush();
        bos.close();
      }
 catch (      IOException e) {
        e.printStackTrace();
      }
    }
  }
  return true;
}
 

Example 47

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

Source file: ClassnameTest.java

  29 
vote

@Test public void testClassname() throws VerificationException, FileNotFoundException, IOException {
  Verifier verifier=new Verifier(ROOT.getAbsolutePath());
  Properties props=Constants.getSystemProperties();
  props.put("rindirect.classname","MyS");
  verifier.setSystemProperties(props);
  verifier.executeGoal("package");
  verifier.verifyTextInLog("BUILD SUCCESS");
  Helper.checkExecution(verifier);
  verifier.resetStreams();
  File result=new File(ROOT + Constants.GENERATE_FOLDER + "/my/application/MyS.java");
  Assert.assertTrue(result.exists());
}
 

Example 48

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

Source file: MobeelizerApplication.java

  29 
vote

public static MobeelizerApplication createApplicationForTitanium(final Application mobeelizer){
  MobeelizerApplication application=new MobeelizerApplication();
  Properties properties=new Properties();
  try {
    properties.load(application.getDefinitionXmlAsset(mobeelizer,"Resources/mobeelizer.properties"));
  }
 catch (  FileNotFoundException e) {
    throw new IllegalStateException("'mobeelizer.properties' file is required",e);
  }
catch (  IOException e) {
    throw new IllegalStateException(e.getMessage(),e);
  }
  String device=properties.getProperty("device");
  String developmentRole=properties.getProperty("role");
  String definitionXml=properties.getProperty("definitionXml");
  String url=properties.getProperty("url");
  String stringMode=properties.getProperty("mode");
  if (definitionXml == null) {
    definitionXml="application.xml";
  }
  definitionXml="Resources/" + definitionXml;
  application.initApplication(mobeelizer,device,null,developmentRole,definitionXml,1,url,stringMode);
  return application;
}
 

Example 49

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/facebook/extpack/com/facebook/android/.

Source file: AsyncFacebookRunner.java

  29 
vote

/** 
 * Invalidate the current user session by removing the access token in memory, clearing the browser cookies, and calling auth.expireSession through the API. The application will be notified when logout is complete via the callback interface. Note that this method is asynchronous and the callback will be invoked in a background thread; operations that affect the UI will need to be posted to the UI thread or an appropriate handler.
 * @param context The Android context in which the logout should be called: it should be the same context in which the login occurred in order to clear any stored cookies
 * @param listener Callback interface to notify the application when the request has completed.
 * @param state An arbitrary object used to identify the request when it returns to the callback. This has no effect on the request itself.
 */
public void logout(final Context context,final RequestListener listener,final Object state){
  new Thread(){
    @Override public void run(){
      try {
        String response=fb.logout(context);
        if (response.length() == 0 || response.equals("false")) {
          listener.onFacebookError(new FacebookError("auth.expireSession failed"),state);
          return;
        }
        listener.onComplete(response,state);
      }
 catch (      FileNotFoundException e) {
        listener.onFileNotFoundException(e,state);
      }
catch (      MalformedURLException e) {
        listener.onMalformedURLException(e,state);
      }
catch (      IOException e) {
        listener.onIOException(e,state);
      }
    }
  }
.start();
}
 

Example 50

From project android-tether, under directory /facebook/src/com/facebook/android/.

Source file: AsyncFacebookRunner.java

  29 
vote

/** 
 * Invalidate the current user session by removing the access token in memory, clearing the browser cookies, and calling auth.expireSession through the API. The application will be notified when logout is complete via the callback interface. Note that this method is asynchronous and the callback will be invoked in a background thread; operations that affect the UI will need to be posted to the UI thread or an appropriate handler.
 * @param context The Android context in which the logout should be called: it should be the same context in which the login occurred in order to clear any stored cookies
 * @param listener Callback interface to notify the application when the request has completed.
 * @param state An arbitrary object used to identify the request when it returns to the callback. This has no effect on the request itself.
 */
public void logout(final Context context,final RequestListener listener,final Object state){
  new Thread(){
    @Override public void run(){
      try {
        String response=fb.logout(context);
        if (response.length() == 0 || response.equals("false")) {
          listener.onFacebookError(new FacebookError("auth.expireSession failed"),state);
          return;
        }
        listener.onComplete(response,state);
      }
 catch (      FileNotFoundException e) {
        listener.onFileNotFoundException(e,state);
      }
catch (      MalformedURLException e) {
        listener.onMalformedURLException(e,state);
      }
catch (      IOException e) {
        listener.onIOException(e,state);
      }
    }
  }
.start();
}
 

Example 51

From project android-thaiime, under directory /latinime/src/com/sugree/inputmethod/latin/.

Source file: BinaryDictionaryFileDumper.java

  29 
vote

/** 
 * Helper method to encapsulate exception handling.
 */
private static AssetFileDescriptor openAssetFileDescriptor(final ContentResolver resolver,final Uri uri){
  try {
    return resolver.openAssetFileDescriptor(uri,"r");
  }
 catch (  FileNotFoundException e) {
    Log.e(TAG,"Could not find a word list from the dictionary provider.");
    return null;
  }
}
 

Example 52

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

Source file: VpnServiceBinder.java

  29 
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 53

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

Source file: Client.java

  29 
vote

/** 
 * Only downloads as much as boundaries of the image in order to find out its size.
 * @param manager Postback manager
 * @param url URL to primary cover
 * @param size Minmal size to pre-resize to.
 * @return
 */
private BitmapFactory.Options prefetch(INotifiableManager manager,String url,int size){
  BitmapFactory.Options opts=new BitmapFactory.Options();
  try {
    InputStream is=new BufferedInputStream(mConnection.getThumbInputStreamForMicroHTTPd(url,manager),8192);
    opts.inJustDecodeBounds=true;
    BitmapFactory.decodeStream(is,null,opts);
  }
 catch (  FileNotFoundException e) {
    return opts;
  }
  return opts;
}
 

Example 54

From project AndroidCommon, under directory /src/com/asksven/andoid/common/contrib/.

Source file: Util.java

  29 
vote

public static boolean writeStoreFile(Context context,int uid,int execUid,String cmd,int allow){
  File storedDir=new File(context.getFilesDir().getAbsolutePath() + File.separator + "stored");
  storedDir.mkdirs();
  if (cmd == null) {
    Log.d(TAG,"App stored for logging purposes, file not required");
    return false;
  }
  String fileName=uid + "-" + execUid;
  try {
    OutputStreamWriter out=new OutputStreamWriter(new FileOutputStream(new File(storedDir.getAbsolutePath() + File.separator + fileName)));
    out.write(cmd);
    out.write('\n');
    out.write(String.valueOf(allow));
    out.write('\n');
    out.flush();
    out.close();
  }
 catch (  FileNotFoundException e) {
    Log.w(TAG,"Store file not written",e);
    return false;
  }
catch (  IOException e) {
    Log.w(TAG,"Store file not written",e);
    return false;
  }
  return true;
}
 

Example 55

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

Source file: ImageUtilities.java

  29 
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 56

From project AndroidLab, under directory /samples/AndroidLdapClient/src/com/unboundid/android/ldap/client/.

Source file: ServerInstance.java

  29 
vote

/** 
 * Retrieves a map of all defined server instances, mapped from the instance ID to the instance object.
 * @param context  The application context.  It must not be {@code null}.
 * @return  A map of all defined server instances.
 * @throws IOException  If a problem occurs while reading information aboutthe defined instances.
 */
public static Map<String,ServerInstance> getInstances(final Context context) throws IOException {
  logEnter(LOG_TAG,"getInstances",context);
  final LinkedHashMap<String,ServerInstance> instances=new LinkedHashMap<String,ServerInstance>(1);
  BufferedReader reader=null;
  try {
    try {
      logDebug(LOG_TAG,"getInstances","Attempting to open file {0} for reading",INSTANCE_FILE_NAME);
      reader=new BufferedReader(new InputStreamReader(context.openFileInput(INSTANCE_FILE_NAME)),1024);
    }
 catch (    final FileNotFoundException fnfe) {
      logException(LOG_TAG,"getInstances",fnfe);
      return logReturn(LOG_TAG,"getInstances",Collections.unmodifiableMap(instances));
    }
    while (true) {
      final String line=reader.readLine();
      logDebug(LOG_TAG,"getInstances","read line {0}",line);
      if (line == null) {
        break;
      }
      if (line.length() == 0) {
        continue;
      }
      final ServerInstance i=decode(line);
      instances.put(i.getID(),i);
    }
    return logReturn(LOG_TAG,"getInstances",Collections.unmodifiableMap(instances));
  }
  finally {
    if (reader != null) {
      logDebug(LOG_TAG,"getInstances","closing reader");
      reader.close();
    }
  }
}
 

Example 57

From project AndroidSensorLogger, under directory /src/com/sstp/androidsensorlogger/.

Source file: CameraActivity.java

  29 
vote

private static void Save_to_SD(Bitmap bm,String image_name){
  File extStorageDirectory=Environment.getExternalStorageDirectory();
  String meteoDirectory_path=extStorageDirectory + "/space";
  OutputStream outStream=null;
  File file=new File(meteoDirectory_path,"/" + image_name);
  try {
    outStream=new FileOutputStream(file);
    bm.compress(Bitmap.CompressFormat.PNG,100,outStream);
    outStream.flush();
    outStream.close();
    Log.i("Hub","OK, Image Saved to SD");
    Log.i("Hub","height = " + bm.getHeight() + ", width = "+ bm.getWidth());
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
    Log.i("Hub","FileNotFoundException: " + e.toString());
  }
catch (  IOException e) {
    e.printStackTrace();
    Log.i("Hub","IOException: " + e.toString());
  }
}
 

Example 58

From project android_build, under directory /tools/droiddoc/src/.

Source file: Stubs.java

  29 
vote

static void writeClassFile(String stubsDir,ClassInfo cl){
  if (cl.containingClass() != null) {
    return;
  }
  if (cl.containingPackage() != null && cl.containingPackage().name().equals("")) {
    return;
  }
  String filename=stubsDir + '/' + javaFileName(cl);
  File file=new File(filename);
  ClearPage.ensureDirectory(file);
  PrintStream stream=null;
  try {
    stream=new PrintStream(file);
    writeClassFile(stream,cl);
  }
 catch (  FileNotFoundException e) {
    System.err.println("error writing file: " + filename);
  }
 finally {
    if (stream != null) {
      stream.close();
    }
  }
}
 

Example 59

From project android_device_samsung_galaxys2, under directory /DeviceSettings/src/com/cyanogenmod/settings/device/.

Source file: Utils.java

  29 
vote

/** 
 * Write a string value to the specified file.
 * @param filename      The filename
 * @param value         The value
 */
public static void writeValue(String filename,String value){
  try {
    FileOutputStream fos=new FileOutputStream(new File(filename));
    fos.write(value.getBytes());
    fos.flush();
    fos.getFD().sync();
    fos.close();
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 60

From project android_device_samsung_galaxys2_1, under directory /DeviceSettings/src/com/cyanogenmod/settings/device/.

Source file: Utils.java

  29 
vote

/** 
 * Write a string value to the specified file.
 * @param filename      The filename
 * @param value         The value
 */
public static void writeValue(String filename,String value){
  try {
    FileOutputStream fos=new FileOutputStream(new File(filename));
    fos.write(value.getBytes());
    fos.flush();
    fos.getFD().sync();
    fos.close();
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 61

From project android_device_samsung_i777, under directory /DeviceSettings/src/com/cyanogenmod/settings/device/.

Source file: Utils.java

  29 
vote

/** 
 * Write a string value to the specified file.
 * @param filename      The filename
 * @param value         The value
 */
public static void writeValue(String filename,String value){
  try {
    FileOutputStream fos=new FileOutputStream(new File(filename));
    fos.write(value.getBytes());
    fos.flush();
    fos.getFD().sync();
    fos.close();
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 62

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

Source file: Parser.java

  29 
vote

/** 
 * Turns off data capture; writes the captured data to a specified file.
 */
public void captureOff(Context context,String file){
  try {
    FileOutputStream out=context.openFileOutput(file,Context.MODE_WORLD_WRITEABLE);
    out.write(captureArray.toString().getBytes());
    out.close();
  }
 catch (  FileNotFoundException e) {
  }
catch (  IOException e) {
  }
}
 

Example 63

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

Source file: BaseImage.java

  29 
vote

private void setupDimension(){
  ParcelFileDescriptor input=null;
  try {
    input=mContentResolver.openFileDescriptor(mUri,"r");
    BitmapFactory.Options options=new BitmapFactory.Options();
    options.inJustDecodeBounds=true;
    BitmapManager.instance().decodeFileDescriptor(input.getFileDescriptor(),options);
    mWidth=options.outWidth;
    mHeight=options.outHeight;
  }
 catch (  FileNotFoundException ex) {
    mWidth=0;
    mHeight=0;
  }
 finally {
    Util.closeSilently(input);
  }
}
 

Example 64

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

Source file: DiskCache.java

  29 
vote

private RandomAccessFile getChunkFile(int chunk){
  RandomAccessFile chunkFile=null;
synchronized (mChunkFiles) {
    chunkFile=mChunkFiles.get(chunk);
  }
  if (chunkFile == null) {
    final String chunkFilePath=mCacheDirectoryPath + CHUNK_FILE_PREFIX + chunk;
    try {
      chunkFile=new RandomAccessFile(chunkFilePath,"rw");
    }
 catch (    FileNotFoundException e) {
      Log.e(TAG,"Unable to create or open the chunk file " + chunkFilePath);
    }
synchronized (mChunkFiles) {
      mChunkFiles.put(chunk,chunkFile);
    }
  }
  return chunkFile;
}
 

Example 65

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

Source file: Device.java

  29 
vote

private void ensureAttributeUtilsAvailability(){
  String[] symlinks={"test","lsattr","chattr"};
  try {
    mContext.openFileInput("busybox");
    for (    String s : symlinks)     mContext.openFileInput(s);
  }
 catch (  FileNotFoundException notfoundE) {
    Log.d(TAG,"Extracting tools from assets is required");
    try {
      Util.copyFromAssets(mContext,"busybox-armeabi","busybox");
      String filesPath=mContext.getFilesDir().getAbsolutePath();
      String script="chmod 700 " + filesPath + "/busybox\n";
      for (      String s : symlinks) {
        script+="rm " + filesPath + "/"+ s+ "\n";
        script+="ln -s busybox " + filesPath + "/"+ s+ "\n";
      }
      Util.run(script);
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
  }
}
 

Example 66

From project android_packages_inputmethods_LatinIME, under directory /java/src/com/android/inputmethod/latin/.

Source file: BinaryDictionaryFileDumper.java

  29 
vote

/** 
 * Helper method to encapsulate exception handling.
 */
private static AssetFileDescriptor openAssetFileDescriptor(final ContentResolver resolver,final Uri uri){
  try {
    return resolver.openAssetFileDescriptor(uri,"r");
  }
 catch (  FileNotFoundException e) {
    Log.e(TAG,"Could not find a word list from the dictionary provider.");
    return null;
  }
}
 

Example 67

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

Source file: LogHelper.java

  29 
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 68

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

Source file: DownloadManagerService.java

  29 
vote

private String unzipSharedDeckFile(String zipFilename,String title){
  ZipInputStream zipInputStream=null;
  Log.i(AnkiDroidApp.TAG,"unzipSharedDeckFile");
  if (zipFilename.endsWith(".zip")) {
    Log.i(AnkiDroidApp.TAG,"zipFilename ends with .zip");
    try {
      zipInputStream=new ZipInputStream(new FileInputStream(new File(zipFilename)));
      title=title.replace("^","");
      title=title.substring(0,java.lang.Math.min(title.length(),40));
      if (new File(mDestination + "/" + title+ ".anki").exists()) {
        title+=System.currentTimeMillis();
      }
      String partialDeckPath=mDestination + "/tmp/" + title;
      String deckFilename=partialDeckPath + ".anki.updating";
      ZipEntry zipEntry=null;
      while ((zipEntry=zipInputStream.getNextEntry()) != null) {
        Log.i(AnkiDroidApp.TAG,"zipEntry = " + zipEntry.getName());
        if ("shared.anki".equalsIgnoreCase(zipEntry.getName())) {
          Utils.writeToFile(zipInputStream,deckFilename);
        }
 else         if (zipEntry.getName().startsWith("shared.media/",0)) {
          Log.i(AnkiDroidApp.TAG,"Folder created = " + new File(partialDeckPath + ".media/").mkdir());
          Log.i(AnkiDroidApp.TAG,"Destination = " + AnkiDroidApp.getStorageDirectory() + "/"+ title+ ".media/"+ zipEntry.getName().replace("shared.media/",""));
          Utils.writeToFile(zipInputStream,partialDeckPath + ".media/" + zipEntry.getName().replace("shared.media/",""));
        }
      }
      zipInputStream.close();
      new File(zipFilename).delete();
    }
 catch (    FileNotFoundException e) {
      Log.e(AnkiDroidApp.TAG,"FileNotFoundException = " + e.getMessage());
      e.printStackTrace();
    }
catch (    IOException e) {
      Log.e(AnkiDroidApp.TAG,"IOException = " + e.getMessage());
      e.printStackTrace();
    }
  }
  return title;
}
 

Example 69

From project ANNIS, under directory /annis-service/src/main/java/annis/administration/.

Source file: MediaImportPreparedStatementCallbackImpl.java

  29 
vote

public MediaImportPreparedStatementCallbackImpl(String absolutePath,long corpusRef,Map<String,String> mimeTypeMapping){
  try {
    this.file=new File(absolutePath);
    fileStream=new FileInputStream(file);
    String fileEnding=FilenameUtils.getExtension(absolutePath);
    if (mimeTypeMapping.containsKey(fileEnding)) {
      this.mimeType=mimeTypeMapping.get(fileEnding);
    }
 else {
      this.mimeType=new MimetypesFileTypeMap().getContentType(file);
    }
    this.corpusRef=corpusRef;
  }
 catch (  FileNotFoundException ex) {
    log.error(null,ex);
  }
}
 

Example 70

From project ant4eclipse, under directory /org.ant4eclipse.ant.core/src/org/ant4eclipse/ant/core/.

Source file: AntCall.java

  29 
vote

/** 
 * {@inheritDoc}<p> Overrides the <code>execute()</code> method of the  {@link Ant} super class. This method will return <b>without</b>an exception if the defined ant file or the defined target is not available. </p>
 */
@Override public void execute() throws BuildException {
  AntConfigurator.configureAnt4Eclipse(getProject());
  try {
    super.execute();
  }
 catch (  BuildException buildException) {
    Throwable cause=getCause(buildException);
    if (cause instanceof FileNotFoundException && (cause.getMessage().indexOf(getAntFile()) != -1 || getAntFile() == null)) {
    }
 else     if ((buildException.getMessage().indexOf("does not exist in the project") != -1)) {
      buildException.printStackTrace();
    }
 else {
      throw buildException;
    }
  }
}
 

Example 71

From project AntiCheat, under directory /src/main/java/net/h31ix/anticheat/util/yaml/.

Source file: CommentedConfiguration.java

  29 
vote

public static CommentedConfiguration loadConfig(File file){
  CommentedConfiguration config=new CommentedConfiguration();
  try {
    config.load(file);
  }
 catch (  FileNotFoundException ex) {
  }
catch (  IOException ex) {
    Bukkit.getLogger().log(Level.SEVERE,"Cannot load " + file,ex);
  }
catch (  InvalidConfigurationException ex) {
    Bukkit.getLogger().log(Level.SEVERE,"Cannot load " + file,ex);
  }
  return config;
}
 

Example 72

From project any23, under directory /core/src/main/java/org/apache/any23/cli/.

Source file: Rover.java

  29 
vote

protected void configure(){
  try {
    tripleHandler=WriterFactoryRegistry.getInstance().getWriterInstanceByIdentifier(format,outputStream);
  }
 catch (  Exception e) {
    throw new NullPointerException(format("Invalid output format '%s', admitted values: %s",format,FORMATS));
  }
  if (logFile != null) {
    try {
      tripleHandler=new LoggingTripleHandler(tripleHandler,new PrintWriter(logFile));
    }
 catch (    FileNotFoundException fnfe) {
      throw new IllegalArgumentException(format("Can not write to log file [%s]",logFile),fnfe);
    }
  }
  if (statistics) {
    benchmarkTripleHandler=new BenchmarkTripleHandler(tripleHandler);
    tripleHandler=benchmarkTripleHandler;
  }
  if (noTrivial) {
    tripleHandler=new IgnoreAccidentalRDFa(new IgnoreTitlesOfEmptyDocuments(tripleHandler),true);
  }
  reportingTripleHandler=new ReportingTripleHandler(tripleHandler);
  final Configuration configuration=DefaultConfiguration.singleton();
  extractionParameters=pedantic ? new ExtractionParameters(configuration,ValidationMode.ValidateAndFix,nestingDisabled) : new ExtractionParameters(configuration,ValidationMode.None,nestingDisabled);
  if (defaultns != null) {
    extractionParameters.setProperty(ExtractionParameters.EXTRACTION_CONTEXT_URI_PROPERTY,defaultns);
  }
  any23=(extractors.isEmpty()) ? new Any23() : new Any23(extractors.toArray(new String[extractors.size()]));
  any23.setHTTPUserAgent(Any23.DEFAULT_HTTP_CLIENT_USER_AGENT + "/" + Any23.VERSION);
}