List of usage examples for java.io FileReader read
public int read(java.nio.CharBuffer target) throws IOException
From source file:FileViewer.java
/** * Load and display the specified file from the specified directory *///ww w . ja v a 2 s . c om public void setFile(String directory, String filename) { if ((filename == null) || (filename.length() == 0)) return; File f; FileReader in = null; // Read and display the file contents. Since we're reading text, we // use a FileReader instead of a FileInputStream. try { f = new File(directory, filename); // Create a file object in = new FileReader(f); // And a char stream to read it char[] buffer = new char[4096]; // Read 4K characters at a time int len; // How many chars read each time textarea.setText(""); // Clear the text area while ((len = in.read(buffer)) != -1) { // Read a batch of chars String s = new String(buffer, 0, len); // Convert to a string textarea.append(s); // And display them } this.setTitle("FileViewer: " + filename); // Set the window title textarea.setCaretPosition(0); // Go to start of file } // Display messages if something goes wrong catch (IOException e) { textarea.setText(e.getClass().getName() + ": " + e.getMessage()); this.setTitle("FileViewer: " + filename + ": I/O Exception"); } // Always be sure to close the input stream! finally { try { if (in != null) in.close(); } catch (IOException e) { } } }
From source file:org.clipsmonitor.monitor2015.RescueGenMap.java
public int[] GetJsonMapDimension(File jsonMap) { try {/*www. j a v a 2s . c om*/ //converto il file in un oggetto JSON FileReader jsonreader = new FileReader(jsonMap); char[] chars = new char[(int) jsonMap.length()]; jsonreader.read(chars); String jsonstring = new String(chars); jsonreader.close(); JSONObject json = new JSONObject(jsonstring); //leggo il numero di celle dalla radice del JSON int NumCellX = Integer.parseInt(json.get("cell_x").toString()); int NumCellY = Integer.parseInt(json.get("cell_y").toString()); return new int[] { NumCellX, NumCellY }; } catch (JSONException ex) { AppendLogMessage(ex.getMessage(), "error"); } catch (IOException ex) { AppendLogMessage(ex.getMessage(), "error"); } catch (NumberFormatException ex) { AppendLogMessage(ex.getMessage(), "error"); } return null; }
From source file:org.clipsmonitor.monitor2015.RescueGenMap.java
/** * Legge da un file Json e imposta gli attributi del robot * @param jsonFile //from w w w. j av a 2 s .c o m */ public void LoadJsonRobotParams(File jsonFile) { try { //converto il file in un oggetto JSON FileReader jsonreader = new FileReader(jsonFile); char[] chars = new char[(int) jsonFile.length()]; jsonreader.read(chars); String jsonstring = new String(chars); jsonreader.close(); JSONObject json = new JSONObject(jsonstring); agentposition = new int[] { json.getInt("robot_x"), json.getInt("robot_y") }; defaultagentposition = new int[] { json.getInt("robot_x_default"), json.getInt("robot_y_default") }; direction = json.getString("robot_direction"); loaded = json.getString("robot_loaded"); scene[agentposition[0]][agentposition[1]] += "+" + "agent_" + direction + "_" + loaded; defaulagentcondition = scene[agentposition[0]][agentposition[1]]; move = clone(scene); CopyToActive(scene); } catch (JSONException ex) { AppendLogMessage(ex.getMessage(), "error"); } catch (IOException ex) { AppendLogMessage(ex.getMessage(), "error"); } catch (NumberFormatException ex) { AppendLogMessage(ex.getMessage(), "error"); } }
From source file:org.jts.docGenerator.PathInserter.java
/** * * @param hrefs String representations of hrefs for which paths need to be * inserted. it is assumed that file names in href are placed in the * destination root directory.// w w w. j av a2 s .co m * */ void insertPaths(List<String> hrefs) { // get all HTML files at or under dest dir Collection<File> htmlFiles = FileUtils.listFiles(dest, FileFilterUtils.suffixFileFilter(".html"), TrueFileFilter.INSTANCE); FileReader reader = null; FileWriter writer = null; for (File htmlFile : htmlFiles) { try { reader = new FileReader(htmlFile); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } char[] buf = new char[(int) htmlFile.length()]; try { reader.read(buf); reader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } StringBuilder builder = new StringBuilder(); builder = builder.append(buf); // insert paths to specified hrefs for (int jj = 0; jj < hrefs.size(); jj++) { String path = getPath(htmlFile); String href = (String) hrefs.get(jj); int offset = 0; // find all incidences of href and insert path modification while ((offset = builder.indexOf(href, offset)) != -1) { builder = builder.insert(offset, path); offset += path.length() + href.length(); } } try { writer = new FileWriter(htmlFile); writer.write(builder.toString().toCharArray()); writer.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
From source file:org.apache.geode.management.internal.cli.commands.ConfigCommandsDUnitTest.java
@Category(FlakyTest.class) // GEODE-1449 @Test/*w w w .ja v a2 s . c o m*/ public void testExportConfig() throws Exception { Properties localProps = new Properties(); localProps.setProperty(NAME, "Manager"); localProps.setProperty(GROUPS, "Group1"); setUpJmxManagerOnVm0ThenConnect(localProps); // Create a cache in another VM (VM1) Host.getHost(0).getVM(1).invoke(new SerializableRunnable() { public void run() { Properties localProps = new Properties(); localProps.setProperty(NAME, "VM1"); localProps.setProperty(GROUPS, "Group2"); getSystem(localProps); getCache(); } }); // Create a cache in a 3rd VM (VM2) Host.getHost(0).getVM(2).invoke(new SerializableRunnable() { public void run() { Properties localProps = new Properties(); localProps.setProperty(NAME, "VM2"); localProps.setProperty(GROUPS, "Group2"); getSystem(localProps); getCache(); } }); // Create a cache in the local VM localProps = new Properties(); localProps.setProperty(NAME, "Shell"); getSystem(localProps); Cache cache = getCache(); // Test export config for all members deleteTestFiles(); CommandResult cmdResult = executeCommand( "export config --dir=" + this.temporaryFolder.getRoot().getAbsolutePath()); assertEquals(Result.Status.OK, cmdResult.getStatus()); assertTrue(this.managerConfigFile + " should exist", this.managerConfigFile.exists()); assertTrue(this.managerPropsFile + " should exist", this.managerPropsFile.exists()); assertTrue(this.vm1ConfigFile + " should exist", this.vm1ConfigFile.exists()); assertTrue(this.vm1PropsFile + " should exist", this.vm1PropsFile.exists()); assertTrue(this.vm2ConfigFile + " should exist", this.vm2ConfigFile.exists()); assertTrue(this.vm2PropsFile + " should exist", this.vm2PropsFile.exists()); assertTrue(this.shellConfigFile + " should exist", this.shellConfigFile.exists()); assertTrue(this.shellPropsFile + " should exist", this.shellPropsFile.exists()); // Test exporting member deleteTestFiles(); cmdResult = executeCommand( "export config --member=Manager --dir=" + this.temporaryFolder.getRoot().getAbsolutePath()); assertEquals(Result.Status.OK, cmdResult.getStatus()); assertTrue(this.managerConfigFile + " should exist", this.managerConfigFile.exists()); assertFalse(this.vm1ConfigFile + " should not exist", this.vm1ConfigFile.exists()); assertFalse(this.vm2ConfigFile + " should not exist", this.vm2ConfigFile.exists()); assertFalse(this.shellConfigFile + " should not exist", this.shellConfigFile.exists()); // Test exporting group deleteTestFiles(); cmdResult = executeCommand( "export config --group=Group2 --dir=" + this.temporaryFolder.getRoot().getAbsolutePath()); assertEquals(Result.Status.OK, cmdResult.getStatus()); assertFalse(this.managerConfigFile + " should not exist", this.managerConfigFile.exists()); assertTrue(this.vm1ConfigFile + " should exist", this.vm1ConfigFile.exists()); assertTrue(this.vm2ConfigFile + " should exist", this.vm2ConfigFile.exists()); assertFalse(this.shellConfigFile + " should not exist", this.shellConfigFile.exists()); // Test export to directory deleteTestFiles(); cmdResult = executeCommand("export config --dir=" + this.subDir.getAbsolutePath()); assertEquals(Result.Status.OK, cmdResult.getStatus()); assertFalse(this.managerConfigFile.exists()); assertTrue(this.subManagerConfigFile.exists()); // Test the contents of the file StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); CacheXmlGenerator.generate(cache, printWriter, false, false, false); String configToMatch = stringWriter.toString(); deleteTestFiles(); cmdResult = executeCommand( "export config --member=Shell --dir=" + this.temporaryFolder.getRoot().getAbsolutePath()); assertEquals(Result.Status.OK, cmdResult.getStatus()); char[] fileContents = new char[configToMatch.length()]; FileReader reader = new FileReader(this.shellConfigFile); reader.read(fileContents); assertEquals(configToMatch, new String(fileContents)); }
From source file:fridgegameinstaller.installation.java
public String getLocalModpackVersion() { System.out.println(mcloc + "/fridgegame_version.fg"); File fgver = new File(mcloc + "/fridgegame_version.fg"); String ver = null;/* w ww . ja va 2 s. c o m*/ if (fgver.exists()) { try { FileReader reader = new FileReader(fgver); char[] chars = new char[(int) fgver.length()]; reader.read(chars); ver = new String(chars); reader.close(); } catch (IOException e) { e.printStackTrace(); mainFrame.errorMsg("An error occured while reading Modpack version.More information in the log", "Error"); mainFrame.setFormToPostInstallation(); } } else { ver = "0"; } System.out.println(ver); return ver; }
From source file:ca.uvic.cs.tagsea.statistics.svn.jobs.SVNCommentScanningJob.java
protected IStatus run(IProgressMonitor monitor) { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); ISVNClientAdapter client;/* w w w . ja v a2 s.c o m*/ List svnResources = new LinkedList(); for (int i = 0; i < projects.length; i++) { IProject project = projects[i]; ISVNLocalResource r = SVNWorkspaceRoot.getSVNResourceFor(project); try { if (r != null && r.isManaged()) { svnResources.add(r); } } catch (SVNException e) { //do nothing, continue t the next } } monitor.beginTask("Scanning subversion projects...", svnResources.size() * 1000000); IPath state = SVNStatistics.getDefault().getStateLocation(); File tempdir = state.append("temp").toFile(); if (!tempdir.isDirectory()) { if (tempdir.exists()) { tempdir.delete(); } tempdir.mkdir(); } deleteTemps(tempdir); for (Iterator it = svnResources.iterator(); it.hasNext();) { ISVNLocalResource svnProject = (ISVNLocalResource) it.next(); //used to make sure that we don't repeat old comments. HashMap fileCommentsMap = new HashMap(); fileEntryMap = new HashMap(); monitor.subTask("Getting project information for " + svnProject.getName()); //create a temp file for each project. They will be uploaded //to the server. String projectName = svnProject.getName(); //names are guaranteed unique try { ISVNRemoteResource remote = null; for (int tries = 0; remote == null && tries < 10; tries++) { try { remote = svnProject.getLatestRemoteResource(); } catch (Exception e) { } ; if (remote == null) { SVNStatistics.getDefault().getLog().log(new Status(IStatus.WARNING, SVNStatistics.PLUGIN_ID, IStatus.WARNING, "could not get remote resource for " + svnProject.getName() + "... trying again.", null)); try { // @tag tagsea.bug.subclipse : it seems that sublcipse has a synchronization problem. Wait a little while and try again. Thread.sleep(1000); } catch (InterruptedException e1) { return new Status(IStatus.ERROR, SVNProviderPlugin.ID, IStatus.ERROR, "Could not communicate with remote resource.", null); } } } if (remote == null) { SVNStatistics.getDefault().getLog().log(new Status(IStatus.ERROR, SVNStatistics.PLUGIN_ID, 0, "Could not get a remote resource", null)); monitor.worked(1000000); continue; } ISVNRepositoryLocation repository = remote.getRepository(); client = repository.getSVNClient(); // @tag tagsea.statistics.enhance : It seems best to use this password callback because that way, the passwords can be saved with the workspace. But, it might be confusing to see for the first time. client.addPasswordCallback(SVNProviderPlugin.getPlugin().getSvnPromptUserPassword()); SVNRevision.Number revision = remote.getLastChangedRevision(); long revNum = revision.getNumber(); int revisionWork = 1000000; ILogEntry[] entries; try { entries = remote.getLogEntries(new NullProgressMonitor()); } catch (TeamException e1) { monitor.worked(revisionWork); e1.printStackTrace(); continue; } if (revNum > 0) { revisionWork = 1000000 / (int) revNum; } for (int ei = 0; ei < entries.length; ei++) { ILogEntry entry = entries[ei]; revision = entry.getRevision(); File tempFile = state.append( projectName + "." + getDateString() + "." + revision.getNumber() + ".comments.txt") .toFile(); if (tempFile.exists()) { tempFile.delete(); } try { tempFile.createNewFile(); } catch (IOException e) { //skip to the next one. continue; } PrintStream out; try { out = new PrintStream(tempFile); } catch (IOException e) { continue; } out.println(remote.getUrl() + " Revision:" + revision.getNumber()); monitor.subTask("Finding java resources: " + svnProject.getName() + "..."); SubProgressMonitor revMonitor = new SubProgressMonitor(monitor, revisionWork); if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } monitor.subTask("temporarily checking out " + svnProject.getName() + "..."); SubProgressMonitor subPm = new SubProgressMonitor(revMonitor, 10); try { OperationManager.getInstance().beginOperation(client, new OperationProgressNotifyListener(subPm)); client.checkout(remote.getUrl(), new File(tempdir, svnProject.getName()), revision, true); } catch (SVNClientException e) { //I wish that there were a better way to do this, but it seem that we //have to just keep decrementing it. revMonitor.done(); revNum--; revision = new SVNRevision.Number(revNum); continue; } finally { OperationManager.getInstance().endOperation(); subPm.done(); } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } List files = findJavaFiles(tempdir); int work = 0; if (files.size() > 0) { work = (revisionWork - 20) / files.size(); for (Iterator fit = files.iterator(); fit.hasNext();) { File file = (File) fit.next(); monitor.subTask("Scanning java file...."); TreeSet commentSet = (TreeSet) fileCommentsMap.get(file.getAbsolutePath()); if (commentSet == null) { commentSet = new TreeSet(); fileCommentsMap.put(file.getAbsolutePath(), commentSet); } FileReader reader = new FileReader(file); StringBuilder builder = new StringBuilder(); char[] buffer = new char[1024]; int read = 0; while ((read = reader.read(buffer)) >= 0) { builder.append(buffer, 0, read); } reader.close(); ISVNAnnotations ann = null; try { //get blame information. List fileLogs = getLogEntries(file, client, repository); //don't do extra work if this file doesn't have a log for this revision. if (!checkRevision(fileLogs, revision)) { monitor.worked(work); //System.out.println("Skipped " + file.getAbsolutePath() + " revision " + revision.getNumber()); continue; } ann = client.annotate(file, revision, revision); } catch (SVNClientException e) { } catch (TeamException e) { } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } SubProgressMonitor scanMonitor = new SubProgressMonitor(revMonitor, work); Stats s = SimpleJavaCodeScanner.scan(builder.toString(), scanMonitor); if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } monitor.worked(work); out.println("New/Changed Tags:"); for (int ci = 0; ci < s.TAGS.length; ci++) { Comment c = s.TAGS[ci]; if (!commentSet.contains(c)) { commentSet.add(c); String author = getAuthor(c, ann); out.println(c.toString() + "\tauthor=" + author); } } out.println("New/Changed Tasks:"); for (int ci = 0; ci < s.TASKS.length; ci++) { Comment c = s.TASKS[ci]; if (!commentSet.contains(c)) { commentSet.add(c); String author = getAuthor(c, ann); out.println(c.toString() + "\tauthor=" + author); } } out.println("New/Changed Other:"); for (int ci = 0; ci < s.NONTAGS.length; ci++) { Comment c = s.NONTAGS[ci]; if (!commentSet.contains(c)) { commentSet.add(c); String author = getAuthor(c, ann); out.println(c.toString() + "\tauthor=" + author); } } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } } } if (work == 0) { revMonitor.worked(revisionWork - 10); } monitor.subTask("Sending and Deleting temporary files..."); out.close(); sendFile(tempFile); deleteTemps(tempdir); if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } revMonitor.done(); monitor.worked(revisionWork - 20); } } catch (SVNException e) { return new Status(IStatus.ERROR, SVNStatistics.PLUGIN_ID, 0, e.getMessage(), e); } catch (IOException e) { return new Status(IStatus.ERROR, SVNStatistics.PLUGIN_ID, 0, e.getMessage(), e); } } return Status.OK_STATUS; }
From source file:com.sun.socialsite.business.impl.JPAAppManagerImpl.java
public GadgetSpec getGadgetSpecByURL(URL url) throws SocialSiteException { if (url == null) { throw new SocialSiteException("url is null"); }/* w w w.j a v a2s . co m*/ try { URI javaUri = url.toURI(); Uri shindigUri = Uri.fromJavaUri(javaUri); String specContents = null; if (javaUri.getScheme().equals("file")) { // TODO: Have a property to control whether these are allowed? File file = new File(javaUri); StringBuilder sb = new StringBuilder((int) (file.length())); FileReader reader = new FileReader(file); char[] buf = new char[8192]; int len; while ((len = reader.read(buf)) != -1) { sb.append(buf, 0, len); } specContents = sb.toString(); } else { HttpRequest request = new HttpRequest(shindigUri); request.setIgnoreCache(false); HttpResponse response = gadgetSpecFetcher.fetch(request); specContents = response.getResponseAsString(); if ((response.getHttpStatusCode() != HttpResponse.SC_OK) && (log.isWarnEnabled())) { String msg = String.format("GadgetSpec HTTP Response:%n%s", response.toString()); log.warn(msg); } //else if (log.isDebugEnabled()) { //String msg = String.format("GadgetSpec HTTP Response:%n%s", response.toString()); //log.debug(msg); //} } return new GadgetSpec(shindigUri, specContents); } catch (Exception e) { String msg = String.format("Failed to Retrieve GadgetSpec[%s]", url); throw new SocialSiteException(msg, e); } }
From source file:gov.nih.nci.ncicb.tcga.dcc.dam.processors.FilePackagerFastTest.java
private void checkTar(final File f_tar, final Boolean isMafArchive) throws IOException { FileReader origReader = null; TarArchiveInputStream tarIn = null;/*from ww w . j a v a 2s . co m*/ try { //we're going to open each of the included files in turn and compare to our tiny //original input file. So first, need to read the original file into a string. StringBuilder origBuf = new StringBuilder(); char[] cbuf = new char[1024]; //noinspection IOResourceOpenedButNotSafelyClosed origReader = new FileReader(THIS_FOLDER + TEST_DOWNLOADFILE); int iread; while ((iread = origReader.read(cbuf)) != -1) { for (int i = 0; i < iread; i++) { origBuf.append(cbuf[i]); } } String origText = origBuf.toString(); //noinspection IOResourceOpenedButNotSafelyClosed tarIn = new TarArchiveInputStream(new FileInputStream(f_tar)); TarArchiveEntry entry; int i = 0; entry = tarIn.getNextTarEntry(); assertEquals("file_manifest.txt", entry.getName()); if (isMafArchive) { entry = tarIn.getNextTarEntry(); assertEquals("README_DCC.txt", entry.getName()); } while ((entry = tarIn.getNextTarEntry()) != null) { //compare to input file File expectedName = new File("platform" + i + "/center" + i + "/Level_1/f" + i + ".idat"); assertEquals(expectedName, new File(entry.getName())); byte[] content = new byte[2056]; OutputStream byteOut = new ByteArrayOutputStream(2056); //noinspection ResultOfMethodCallIgnored tarIn.read(content); byteOut.write(content); byteOut.close(); assertEquals(origText, byteOut.toString().trim()); i++; } assertEquals(i, HOWMANYFILES); } finally { IOUtils.closeQuietly(origReader); IOUtils.closeQuietly(tarIn); } }
From source file:org.squidy.designer.model.NodeShape.java
@Override protected boolean changeTitle(String oldTitle, String newTitle) { try {//from www . j a va 2 s . c om URL sourceCodeUrl = SourceCodeUtils.getSourceCode(getProcessable()); // Check if title changed. File sourceCodeFile; if (!oldTitle.equals(newTitle)) { sourceCodeFile = new File(sourceCodeUrl.getFile().replace(oldTitle, newTitle)); // Check if class already exists at url. if (sourceCodeFile.exists()) { JOptionPane.showMessageDialog(Designer.getInstance(), "Class " + newTitle + " already exists at\n" + sourceCodeFile.toString() + "\nPlease choose a different name.", "Class already exists", JOptionPane.ERROR_MESSAGE); return false; } } else { sourceCodeFile = new File(sourceCodeUrl.getFile()); } // Proof if newTitle matches a Java convenient naming. if (!SourceCodeUtils.isJavaConvenientNaming(newTitle)) { JOptionPane.showMessageDialog(Designer.getInstance(), "Please choose a Java convenient naming.", "Java naming error", JOptionPane.ERROR_MESSAGE); return false; } StringBuilder sb = new StringBuilder(); try { FileReader reader = new FileReader(sourceCodeUrl.getFile()); char[] buffer = new char[8096]; int len; while ((len = reader.read(buffer)) != -1) { sb.append(buffer, 0, len); } } catch (FileNotFoundException e) { publishFailure(e); } catch (IOException e) { publishFailure(e); } String newSourceCode = sb.toString().replace(oldTitle, newTitle); persistCode(sourceCodeFile, newTitle, newSourceCode); } catch (MalformedURLException e) { publishFailure(e); return false; } return super.changeTitle(oldTitle, newTitle); }