Example #1
1
  /**
   * Opens the cache in {@code directory}, creating a cache if none exists there.
   *
   * @param directory a writable directory
   * @param valueCount the number of values per cache entry. Must be positive.
   * @param maxSize the maximum number of bytes this cache should use to store
   * @throws FileNotFoundException
   * @throws IOException if reading or writing the cache directory fails
   */
  DiskLruCacheImpl(File directory, long maxSize, int maxCount) throws IOException {
    this.directory = directory;
    this.maxCount = maxCount;
    this.maxSize = maxSize;

    File indexFile = new File(directory, INDEX_FILE);
    if (indexFile.exists()) {
      try {

        this.indexWriter = new DataOutputStream(new FileOutputStream(indexFile, true));
        this.initIndex(new DataInputStream(new FileInputStream(indexFile)));
        return;
      } catch (Exception indexIsCorrupt) {
        DebugLog.error(
            "DiskLruCache "
                + directory
                + " is corrupt: "
                + indexIsCorrupt.getMessage()
                + ", removing");
        this.clear();
      }
    }
    // create a new empty cache
    directory.mkdirs();
    this.indexWriter = new DataOutputStream(new FileOutputStream(indexFile, true));
    this.rebuildIndex();
  }
 private static AddonRepository registerTempRepository(Furnace furnace, AddonRepositoryMode mode)
     throws IOException {
   File repository = File.createTempFile("furnace-repo", ".tmp");
   repository.delete();
   repository.mkdir();
   return furnace.addRepository(mode, repository);
 }
Example #3
1
 public static int compare(File source, File target) {
   if (source.length() != target.length()) return target.length() > source.length() ? 1 : -1;
   int result = 0;
   try {
     InputStream sourceIn = new FileInputStream(source);
     InputStream targetIn = new FileInputStream(target);
     byte[] buf1 = new byte[1 << 16];
     byte[] buf2 = new byte[1 << 16];
     while (result == 0) {
       int len = sourceIn.read(buf1);
       if (len < 0) break;
       int off = 0, count = 0;
       while (len > 0 && count >= 0) {
         count = targetIn.read(buf2, off, len);
         off += count;
         len -= count;
       }
       if (count < 0) {
         result = 1;
         break;
       }
       for (int i = 0; i < off; i++)
         if (buf1[i] != buf2[i]) {
           result = (buf2[i] & 0xff) - (buf1[i] & 0xff);
           break;
         }
     }
     sourceIn.close();
     targetIn.close();
     return result;
   } catch (IOException e) {
     throw new RuntimeException("Could not compare " + source + " to " + target + ": " + e);
   }
 }
  @Test
  public void testAttributeReaderIndexed() throws IOException {
    URL u = TestData.url(TestCaseSupport.class, SHPFILE);
    File shpFile = DataUtilities.urlToFile(u);

    // open the test shapefile
    // creates both indexed and regular shapefile data store
    ShapefileDataStore indexedstore = new ShapefileDataStore(shpFile.toURI().toURL());

    // get a random feature id from one of the stores
    SimpleFeatureIterator it = indexedstore.getFeatureSource().getFeatures().features();
    FeatureId fid = it.next().getIdentifier();
    it.close();

    // query the datastore
    FilterFactory ff = CommonFactoryFinder.getFilterFactory(null);
    Filter idFilter = ff.id(Collections.singleton(fid));
    final Query query =
        new Query(
            indexedstore.getSchema().getName().getLocalPart(), idFilter, new String[] {testColumn});
    final SimpleFeatureCollection indexedfeatures =
        indexedstore.getFeatureSource().getFeatures(query);

    // compare the results
    SimpleFeatureIterator indexIterator = indexedfeatures.features();
    SimpleFeature indexedFeature = indexIterator.next();
    indexIterator.close();

    // get the value of the duplicate column & compare it against expectation
    assertEquals(expectedValue, indexedFeature.getAttribute(testColumn));

    // cleanup
    indexedstore.dispose();
  }
 public void actionPerformed(ActionEvent evt) {
   try {
     if (m_fileButton.isSelected()) {
       if (m_fileField.getText().equals("")) {
         throw new IOException("No filename entered.");
       }
       File f = new File(m_fileField.getText());
       if (!f.exists()) {
         throw new IOException("File does not exist.");
       }
       file = f;
     } else {
       if (m_urlField.getText().equals("")) {
         throw new IOException("No URL entered.");
       }
       File f = File.createTempFile("fedora-ingest-", null);
       f.deleteOnExit();
       try {
         Administrator.DOWNLOADER.get(m_urlField.getText(), new FileOutputStream(f));
       } catch (Exception e) {
         throw new IOException("Download failed: " + m_urlField.getText());
       }
       url = m_urlField.getText();
       file = f;
     }
     dispose();
   } catch (Exception e) {
     Administrator.showErrorDialog(
         Administrator.getDesktop(), "Import Error", e.getMessage(), e);
   }
 }
  /**
   * Test the deployment operation. This will add and remove a given set of deployment using a
   * composite operation and attaching the streams necessary to the http post message.
   *
   * @param quantity the amount of deployments
   * @param encoded whether to send the operation in the dmr encoded format or not
   * @throws IOException
   */
  private void testDeploymentOperations(final int quantity, final boolean encoded)
      throws IOException {

    // Create the deployment
    final File temp = createTempDeploymentZip();
    try {
      final ModelNode deployment = createCompositeDeploymentOperation(quantity);
      final ContentBody operation = getOperationBody(deployment, encoded);
      final List<ContentBody> streams = new ArrayList<ContentBody>();
      for (int i = 0; i < quantity; i++) {
        streams.add(new FileBody(temp));
      }

      final ModelNode response = executePost(operation, encoded, streams);
      Assert.assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());

    } finally {
      temp.delete();
    }

    // And remove the deployments again
    final ModelNode remove = removeDeploymentsOperation(quantity);
    final ContentBody operation = getOperationBody(remove, encoded);
    final ModelNode response = executePost(operation, encoded);
    Assert.assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());
  }
  public void run(IProgressMonitor progressMonitor)
      throws InvocationTargetException, InterruptedException {
    try {
      boolean isFixedForm = getFortranEditor().isFixedForm();

      IDocument doc = getFortranEditor().getIDocument();
      Reader in = new StringReader(doc.get());
      Reader cppIn = new CPreprocessingReader(getFortranEditor().getIFile(), null, in);
      try {
        File tempFile =
            File.createTempFile(
                "tmp", //$NON-NLS-1$
                isFixedForm ? ".f" : ".f90"); // $NON-NLS-1$ //$NON-NLS-2$
        tempFile.deleteOnExit();
        PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(tempFile)));
        try {
          for (int c = cppIn.read(); c != -1; c = cppIn.read()) out.print((char) c);
        } finally {
          out.close();
        }

        IDE.openEditor(
            Workbench.getInstance().getActiveWorkbenchWindow().getActivePage(),
            tempFile.toURI(),
            FortranEditor.EDITOR_ID,
            true);
      } finally {
        cppIn.close();
      }
    } catch (Exception e) {
      String message = e.getMessage();
      if (message == null) message = e.getClass().getName();
      MessageDialog.openError(getFortranEditor().getShell(), "Error", message); // $NON-NLS-1$
    }
  }
  private void mountFiles(String path, Class<?> clazz) {
    try {
      List<Resource> list = new ArrayList<>();
      String packagePath = clazz.getPackage().getName().replace('.', '/');

      PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      Resource[] res = resolver.getResources("classpath:" + packagePath + "/*.png");
      if (res != null) {
        list.addAll(Arrays.asList(res));
      }
      res = resolver.getResources("classpath:" + packagePath + "/*.gif");
      if (res != null) {
        list.addAll(Arrays.asList(res));
      }

      for (Resource resource : list) {
        URI uri = resource.getURI();
        File file = new File(uri.toString());
        mountResource(
            path + "/" + file.getName(), new SharedResourceReference(clazz, file.getName()));
      }
    } catch (Exception ex) {
      LoggingUtils.logUnexpectedException(LOGGER, "Couldn't mount files", ex);
    }
  }
Example #9
0
 private void executeSingleScenario(final File scenarioFile, final Project p) {
   getLog()
       .info(
           "Executing scenario "
               + scenarioFile.getName()
               + " with sut "
               + p.getProperty("sutFile"));
   try {
     p.fireBuildStarted();
     p.init();
     ProjectHelper helper = ProjectHelper.getProjectHelper();
     p.addReference("ant.projectHelper", helper);
     helper.parse(p, scenarioFile);
     p.executeTarget(p.getDefaultTarget());
   } catch (Exception e) {
     getLog().error("Failed to execute scenario " + scenarioFile.getName());
     getLog().error(e);
   } finally {
     p.fireBuildFinished(null);
   }
   getLog()
       .info(
           "Execution of scenario "
               + scenarioFile.getName()
               + " with sut "
               + p.getProperty("sutFile")
               + " has ended");
   getLog().info("------------------------------------------------------------------------");
 }
Example #10
0
 /**
  * Unregisters all JSP page servlets for a plugin.
  *
  * @param webXML the web.xml file containing JSP page names to servlet class file mappings.
  */
 public static void unregisterServlets(File webXML) {
   if (!webXML.exists()) {
     Log.error(
         "Could not unregister plugin servlets, file "
             + webXML.getAbsolutePath()
             + " does not exist.");
     return;
   }
   // Find the name of the plugin directory given that the webXML file
   // lives in plugins/[pluginName]/web/web.xml
   String pluginName = webXML.getParentFile().getParentFile().getParentFile().getName();
   try {
     SAXReader saxReader = new SAXReader(false);
     saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
     Document doc = saxReader.read(webXML);
     // Find all <servelt-mapping> entries to discover name to URL mapping.
     List names = doc.selectNodes("//servlet-mapping");
     for (int i = 0; i < names.size(); i++) {
       Element nameElement = (Element) names.get(i);
       String url = nameElement.element("url-pattern").getTextTrim();
       // Destroy the servlet than remove from servlets map.
       GenericServlet servlet = servlets.get(pluginName + url);
       if (servlet != null) {
         servlet.destroy();
       }
       servlets.remove(pluginName + url);
       servlet = null;
     }
   } catch (Throwable e) {
     Log.error(e.getMessage(), e);
   }
 }
Example #11
0
  /**
   * Save a stream to a file.
   *
   * <p>If the response could not be saved to the file due, for example, to a network error, the
   * file will not exist when this method returns.
   *
   * @param inputStream the stream whose content will be saved
   * @param targetFile the target file, which will be created if necessary
   * @return true if the operation was successful, false otherwise
   */
  public static boolean saveToFile(final InputStream inputStream, final File targetFile) {
    if (inputStream == null) {
      return false;
    }

    try {
      try {
        final File tempFile = File.createTempFile("download", null, targetFile.getParentFile());
        final FileOutputStream fos = new FileOutputStream(tempFile);
        final boolean written = copy(inputStream, fos);
        fos.close();
        if (written) {
          return tempFile.renameTo(targetFile);
        }
        FileUtils.deleteIgnoringFailure(tempFile);
        return false;
      } finally {
        IOUtils.closeQuietly(inputStream);
      }
    } catch (final IOException e) {
      Log.e("LocalStorage.saveToFile", e);
      FileUtils.deleteIgnoringFailure(targetFile);
    }
    return false;
  }
  private void saveBmpToSd(Bitmap bm, String url) {
    if (bm == null) {
      Log.w(TAG, " trying to savenull bitmap");
      return;
    }
    // 判断sdcard上的空间
    //        if (FREE_SD_SPACE_NEEDED_TO_CACHE >freeSpaceOnSd()) {
    //            Log.w(TAG, "Low free space onsd, do not cache");
    //            return;
    //        }

    File file = new File(Environment.getExternalStorageDirectory() + "/cache/" + MD5(url) + ".jpg");
    try {
      file.createNewFile();
      OutputStream outStream = new FileOutputStream(file);
      bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
      outStream.flush();
      outStream.close();
      Log.i(TAG, "Image saved tosd");
    } catch (FileNotFoundException e) {
      Log.w(TAG, "FileNotFoundException");
    } catch (IOException e) {
      Log.w(TAG, "IOException");
    }
  }
 private void performImport() {
   FileDialog dialog = new FileDialog(this.fDialog.getShell(), SWT.OPEN);
   dialog.setText("Export environment variables to file");
   String file = dialog.open();
   if (file != null) {
     File handle = new File(file);
     if (!handle.exists()) {
       String text = "Selected file not exists.";
       showErrorMessage("Environment import", text);
       return;
     }
     EnvironmentVariable[] vars = null;
     try {
       vars = EnvironmentVariablesFileUtils.load(file);
     } catch (Exception e) {
       showErrorMessage("Environment import", e.getMessage());
     }
     if (vars != null) {
       EnvironmentVariable[] variables = this.fEnvironmentVariablesContentProvider.getVariables();
       Set nvars = new HashSet();
       nvars.addAll(Arrays.asList(vars));
       nvars.addAll(Arrays.asList(variables));
       this.fEnvironmentVariablesContentProvider.setVariables(
           (EnvironmentVariable[]) nvars.toArray(new EnvironmentVariable[nvars.size()]));
     }
   }
 }
 public void print(String filename, String text) throws IOException {
   PrintWriter out = new PrintWriter(filename);
   out.write(text);
   out.close();
   File file = new File(filename);
   System.out.println(file.getPath());
 }
  /** {@inheritDoc} */
  @Override
  public void execute()
      throws InsufficientPermissionsException, NoSuchFileOrDirectory, ExecutionException {
    if (isTrace()) {
      Log.v(TAG, String.format("Creating from %s to %s", this.mSrc, this.mDst)); // $NON-NLS-1$
    }

    File s = new File(this.mSrc);
    File d = new File(this.mDst);
    if (!s.exists()) {
      if (isTrace()) {
        Log.v(TAG, "Result: FAIL. NoSuchFileOrDirectory"); // $NON-NLS-1$
      }
      throw new NoSuchFileOrDirectory(this.mSrc);
    }

    // Copy recursively
    if (!s.renameTo(d)) {
      if (isTrace()) {
        Log.v(TAG, "Result: FAIL. InsufficientPermissionsException"); // $NON-NLS-1$
      }
      throw new InsufficientPermissionsException();
    }

    if (isTrace()) {
      Log.v(TAG, "Result: OK"); // $NON-NLS-1$
    }
  }
    public void run() {
      try {
        done = false;

        final String PATH = "/home/lvuser/AutoRoutineData.ser";
        File file = new File(PATH);

        if (!file.exists()) {
          file.createNewFile();
        } else {
          file.delete();
          file.createNewFile();
        }

        FileOutputStream fileOut = new FileOutputStream(file);
        ObjectOutputStream out = new ObjectOutputStream(fileOut);
        out.writeObject(data);
        out.close();
        fileOut.close();

        Repository.Log.info("Serialized auto routine data: " + data.toString());

        done = true;
      } catch (Exception ex) {
        Repository.Logs.error("Failed to serialize auto routine data", ex);
        done = true;
      }
    }
  public Set /*<FileObject>*/ instantiate(/*ProgressHandle handle*/ ) throws IOException {
    Set<FileObject> resultSet = new LinkedHashSet<FileObject>();
    File dirF = FileUtil.normalizeFile((File) wiz.getProperty("projdir"));
    dirF.mkdirs();

    FileObject template = Templates.getTemplate(wiz);
    FileObject dir = FileUtil.toFileObject(dirF);
    unZipFile(template.getInputStream(), dir);

    // Always open top dir as a project:
    resultSet.add(dir);
    // Look for nested projects to open as well:
    Enumeration<? extends FileObject> e = dir.getFolders(true);
    while (e.hasMoreElements()) {
      FileObject subfolder = e.nextElement();
      if (ProjectManager.getDefault().isProject(subfolder)) {
        resultSet.add(subfolder);
      }
    }

    File parent = dirF.getParentFile();
    if (parent != null && parent.exists()) {
      ProjectChooser.setProjectsFolder(parent);
    }

    return resultSet;
  }
  /**
   * Get the resource name given a full filename.
   *
   * @param fileName the full filename (which must be inside the directory)
   * @return the resource name (i.e., the filename with the directory stripped off)
   */
  String getResourceName(String fileName) {
    // FIXME: there is probably a more robust way to do this

    // Strip off the directory part.
    String dirPath = directory.getPath();
    if (!fileName.startsWith(dirPath)) {
      throw new IllegalStateException("Filename " + fileName + " not inside directory " + dirPath);
    }

    // The problem here is that we need to take the relative part of the filename
    // and break it into components that we can then reconstruct into
    // a resource name (using '/' characters to separate the components).
    // Unfortunately, the File class does not make this task particularly easy.

    String relativeFileName = fileName.substring(dirPath.length());
    File file = new File(relativeFileName);
    LinkedList<String> partList = new LinkedList<String>();
    do {
      partList.addFirst(file.getName());
    } while ((file = file.getParentFile()) != null);

    StringBuilder buf = new StringBuilder();
    for (String part : partList) {
      if (buf.length() > 0) {
        buf.append('/');
      }
      buf.append(part);
    }

    return buf.toString();
  }
 /*     */ public static void backupGame(File zipDestiny, boolean wholegame) /*     */ {
   /*     */ File[] source;
   /*     */ File[] source;
   /*  33 */ if (!wholegame) {
     /*  34 */ ArrayList contents = new ArrayList();
     /*     */
     /*  36 */ File f = MinecraftUtil.getBinFolder();
     /*  37 */ if (f.exists()) {
       /*  38 */ contents.add(f);
       /*     */ }
     /*  40 */ f = MinecraftUtil.getResourcesFolder();
     /*  41 */ if (f.exists()) {
       /*  42 */ contents.add(f);
       /*     */ }
     /*  44 */ f = MinecraftUtil.getLoginFile();
     /*  45 */ if (f.exists()) {
       /*  46 */ contents.add(f);
       /*     */ }
     /*  48 */ f = MinecraftUtil.getOptionsFile();
     /*  49 */ if (f.exists()) {
       /*  50 */ contents.add(f);
       /*     */ }
     /*  52 */ source = (File[]) contents.toArray(new File[contents.size()]);
     /*     */ } else {
     /*  54 */ source = MinecraftUtil.getWorkingDirectory().listFiles();
     /*     */ }
   /*  56 */ backupContents(source, zipDestiny, "minecraft_backup", "mcgame");
   /*     */ }
Example #20
0
  private Firewall initialisePlugin(String defaultAction, RuleInfo[] rules)
      throws IOException, ConfigurationException {
    // Create sample config file
    File confFile = File.createTempFile(getClass().getSimpleName() + "conffile", null);
    confFile.deleteOnExit();
    BufferedWriter buf = new BufferedWriter(new FileWriter(confFile));
    buf.write("<firewall default-action=\"" + defaultAction + "\">\n");
    if (rules != null) {
      for (RuleInfo rule : rules) {
        buf.write("<rule");
        buf.write(" access=\"" + rule.getAccess() + "\"");
        if (rule.getHostname() != null) {
          buf.write(" hostname=\"" + rule.getHostname() + "\"");
        }
        if (rule.getNetwork() != null) {
          buf.write(" network=\"" + rule.getNetwork() + "\"");
        }
        buf.write("/>\n");
      }
    }
    buf.write("</firewall>");
    buf.close();

    // Configure plugin
    FirewallConfiguration config = new FirewallConfiguration();
    config.setConfiguration("", new XMLConfiguration(confFile));
    Firewall plugin = new Firewall();
    plugin.configure(config);
    return plugin;
  }
  /**
   * Call this method to update provisioning profiles from save action. The provisioning profiles
   * from save action are merged into current provisioning profiles list. Then this list is
   * sychnronized with the upload folder.
   *
   * @param provisioningProfilesAfterSave
   */
  public void updateProvisioningProfilesFromSave(
      List<KPPProvisioningProfile> provisioningProfilesFromSave) {
    List<KPPProvisioningProfile> ppsCurrent =
        new ArrayList<KPPProvisioningProfile>(getProvisioningProfiles());
    List<KPPProvisioningProfile> ppsNew =
        new ArrayList<KPPProvisioningProfile>(provisioningProfilesFromSave.size());

    for (KPPProvisioningProfile ppA : provisioningProfilesFromSave) {
      for (KPPProvisioningProfile ppC : ppsCurrent) {
        if (ppC.equals(ppA)) {
          ppsNew.add(ppA);
          ppsCurrent.remove(ppC);
          break;
        }
      }
    }

    if (!ppsCurrent.isEmpty()) {
      // delete provisioning profile from filesystem
      final String folderPath = getUploadDirectoryPath();
      File ppFile;
      for (KPPProvisioningProfile pp : ppsCurrent) {
        ppFile = new File(folderPath + File.separator + pp.getFileName());
        ppFile.delete();
      }
    }

    setProvisioningProfiles(ppsNew);
  }
Example #22
0
  /**
   * This method will return you all locally-cached photos for the requested team. It will then
   * spawn a new background thread, and if Drive is available, it will sync the photos for the
   * requested team only and then notify the requesting activity that it has new photos.
   *
   * <p>Since syncing photos with Drive can take a few seconds, FileUtils.loadTeamPhotos() will
   * immediately call the PhotoRequester's updatePhotos(Bitmap[]) with whatever photos are locally
   * cached for that team, and if FileUtils is able to connect to Drive then it will call it again
   * after performing the sync.
   *
   * @param teamNumber The team whos photos we want to load.
   * @param requester The activity that is requesting the photos. This activity's
   *     .updatePhotos(Bitmap[]) will be called with the loaded photos.
   * @return It will call requester.updatePhotos(Bitmap[]) with an array of Bitmaps containing all
   *     photos for that team, or a zero-length array if no photos were found for that team.
   */
  public void getTeamPhotos(int teamNumber, PhotoRequester requester) {
    // check for STORAGE permission
    if (!canWriteToStorage()) return;

    /* First, return the requester any photos we have on the local drive */

    File photosDir = new File(mLocalTeamPhotosFilePath + "/" + teamNumber);

    // check if that folder exists
    if (!photosDir.isDirectory()) {
      // we have no photos for this team
      requester.updatePhotos(new Bitmap[0]);
      return;
    }

    File[] listOfFiles = photosDir.listFiles();
    ArrayList<Bitmap> arrBitmaps = new ArrayList<Bitmap>();
    for (int i = 0; i < listOfFiles.length; i++) {
      if (listOfFiles[i].isFile()) {
        // BitmapFactory will return `null` if the file cannot be parsed as an image, so no
        // error-checking needed.
        Bitmap bitmap = BitmapFactory.decodeFile(listOfFiles[i].getPath());
        if (bitmap != null) arrBitmaps.add(bitmap);
      }
      // else: if it's not a file, then what is it???? .... skip I guess
    }
    requester.updatePhotos(arrBitmaps.toArray(new Bitmap[arrBitmaps.size()]));

    /* Now, attempt to sync with Drive */
    if (canConnectToDrive()) {
      (new TeamPhotoSyncerThread(teamNumber, requester)).start();
    }
  }
 public void sendStaticResource() throws IOException {
   byte[] bytes = new byte[BUFFER_SIZE];
   FileInputStream fis = null;
   try {
     File file = new File(HttpServer.WEB_ROOT, request.getUri());
     if (file.exists()) {
       fis = new FileInputStream(file);
       int ch = fis.read(bytes, 0, BUFFER_SIZE);
       while (ch != -1) {
         output.write(bytes, 0, ch);
         ch = fis.read(bytes, 0, BUFFER_SIZE);
       }
     } else {
       // file not found
       String errorMessage =
           "HTTP/1.1 404 File Not Found\r\n"
               + "Content-Type: text/html\r\n"
               + "Content-Length: 23\r\n"
               + "\r\n"
               + "<h1>File Not Found</h1>";
       output.write(errorMessage.getBytes());
     }
   } catch (Exception e) {
     // thrown if cannot instantiate a File object
     System.out.println(e.toString());
   } finally {
     if (fis != null) fis.close();
   }
 }
Example #24
0
  /**
   * 读文件的字符串列表,列表的元素是一条线
   *
   * @param 文件路径
   * @param 字符集名称一个支持的名字
   * @return 如果文件不存在,返回null,否则返回文件的内容
   * @throws RuntimeException 如果为空责返回异常
   */
  public static List<String> readFileToList(String filePath, String charsetName) {
    File file = new File(filePath);
    List<String> fileContent = new ArrayList<String>();
    if (file == null || !file.isFile()) {
      return null;
    }

    BufferedReader reader = null;
    try {
      InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
      reader = new BufferedReader(is);
      String line = null;
      while ((line = reader.readLine()) != null) {
        fileContent.add(line);
      }
      reader.close();
      return fileContent;
    } catch (IOException e) {
      throw new RuntimeException("IOException occurred. ", e);
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          throw new RuntimeException("IOException occurred. ", e);
        }
      }
    }
  }
Example #25
0
  static Player getOfflinePlayer(String player, UUID uuid) {
    Player pplayer = null;
    try {
      File playerfolder = new File(Bukkit.getWorlds().get(0).getWorldFolder(), "players");

      for (File playerfile : playerfolder.listFiles()) {
        String filename = playerfile.getName();
        String playername = filename.substring(0, filename.length() - 4);

        GameProfile profile = new GameProfile(uuid, playername);

        if (playername.trim().equalsIgnoreCase(player)) {
          MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
          EntityPlayer entity =
              new EntityPlayer(
                  server,
                  server.getWorldServer(0),
                  profile,
                  new PlayerInteractManager(server.getWorldServer(0)));
          Player target = entity == null ? null : (Player) entity.getBukkitEntity();
          if (target != null) {
            target.loadData();
            return target;
          }
        }
      }
    } catch (Exception e) {
      return null;
    }
    return pplayer;
  }
Example #26
0
  /**
   * 读取文件
   *
   * @param 文件路径
   * @param 字符集名称一个受支持的名称
   * @return 如果文件不存在,返回null,否则返回文件的内容
   * @throws RuntimeException if an error occurs while operator BufferedReader
   */
  public static StringBuilder readFile(String filePath, String charsetName) {
    File file = new File(filePath);
    StringBuilder fileContent = new StringBuilder("");
    if (file == null || !file.isFile()) {
      return null;
    }

    BufferedReader reader = null;
    try {
      InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
      reader = new BufferedReader(is);
      String line = null;
      while ((line = reader.readLine()) != null) {
        if (!fileContent.toString().equals("")) {
          fileContent.append("\r\n");
        }
        fileContent.append(line);
      }
      reader.close();
      return fileContent;
    } catch (IOException e) {
      throw new RuntimeException("IOException occurred. ", e);
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          throw new RuntimeException("IOException occurred. ", e);
        }
      }
    }
  }
Example #27
0
 /**
  * 从文件读取json字符串
  *
  * @param path 目录
  * @param name 文件名称
  * @return 返回字符串
  */
 public static String readJsonFromFile(String path, String name) {
   if (StringUtils.isEmpty(path) || StringUtils.isEmpty(name)) {
     return null;
   }
   String content = "";
   File file = new File(path + name);
   if (!file.exists()) {
     return null;
   }
   InputStream in = null;
   try {
     in = new FileInputStream(file);
     if (in != null) {
       InputStreamReader inputreader = new InputStreamReader(in);
       BufferedReader buffreader = new BufferedReader(inputreader);
       String line;
       // 分行读取
       while ((line = buffreader.readLine()) != null) {
         content += line;
       }
       in.close();
     }
   } catch (IOException e) {
     e.printStackTrace();
     return null;
   }
   return content;
 }
Example #28
0
 /**
  * 读取文件夹大小
  *
  * @param dirPath
  * @return
  */
 public static long GetPathLength(String dirPath) {
   File dir = new File(dirPath);
   if (dir == null || !dir.exists()) {
     return 0;
   }
   return getDirSize(dir);
 }
 private static void openXmlEditor(final IFileStore fileStore, int line, int column, String name) {
   assert fileStore != null;
   IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
   if (window != null) {
     IWorkbenchPage page = window.getActivePage();
     if (page != null) {
       try {
         if (!fileStore.getName().endsWith(".pom")) { // .pom means stuff from local repository?
           IEditorPart part = IDE.openEditorOnFileStore(page, fileStore);
           reveal(selectEditorPage(part), line, column);
         } else {
           // we need special EditorInput for stuff from repository
           name = name + ".pom"; // $NON-NLS-1$
           File file = new File(fileStore.toURI());
           try {
             IEditorInput input =
                 new MavenPathStorageEditorInput(
                     name, name, file.getAbsolutePath(), readStream(new FileInputStream(file)));
             IEditorPart part = OpenPomAction.openEditor(input, name);
             reveal(selectEditorPage(part), line, column);
           } catch (IOException e) {
             log.error("failed opening editor", e);
           }
         }
       } catch (PartInitException e) {
         MessageDialog.openInformation(
             Display.getDefault().getActiveShell(), //
             Messages.PomHyperlinkDetector_error_title,
             NLS.bind(Messages.PomHyperlinkDetector_error_message, fileStore, e.toString()));
       }
     }
   }
 }
Example #30
0
  /**
   * Creates the appropriate HSSFWorkbook / XSSFWorkbook from the given File, which must exist and
   * be readable, and may be password protected
   *
   * <p>Note that in order to properly release resources the Workbook should be closed after use.
   *
   * @throws EncryptedDocumentException If the wrong password is given for a protected file
   * @throws EmptyFileException If an empty stream is given
   */
  public static Workbook create(File file, String password)
      throws IOException, InvalidFormatException, EncryptedDocumentException {
    if (!file.exists()) {
      throw new FileNotFoundException(file.toString());
    }

    try {
      NPOIFSFileSystem fs = new NPOIFSFileSystem(file);
      return create(fs, password);
    } catch (OfficeXmlFileException e) {
      // opening as .xls failed => try opening as .xlsx
      OPCPackage pkg = OPCPackage.open(file);
      try {
        return new XSSFWorkbook(pkg);
      } catch (IOException ioe) {
        // ensure that file handles are closed (use revert() to not re-write the file)
        pkg.revert();
        // pkg.close();

        // rethrow exception
        throw ioe;
      } catch (IllegalArgumentException ioe) {
        // ensure that file handles are closed (use revert() to not re-write the file)
        pkg.revert();
        // pkg.close();

        // rethrow exception
        throw ioe;
      }
    }
  }