Java Code Examples for java.io.IOException
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 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.
Source file: Webserver.java

/** * it closes stream awaring of keep -alive * @throws IOException */ private void closeStreams() throws IOException { IOException ioe=null; try { if (pw != null) pw.flush(); else out.flush(); } catch ( IOException io1) { ioe=io1; } try { out.close(); } catch ( IOException io1) { if (ioe != null) ioe=(IOException)ioe.initCause(io1); else ioe=io1; } try { in.close(); } catch ( IOException io1) { if (ioe != null) ioe=(IOException)ioe.initCause(io1); else ioe=io1; } if (ioe != null) throw ioe; }
Example 2
From project 2Degrees-Toolbox, under directory /ActionBarSherlock/src/com/actionbarsherlock/view/.
Source file: MenuInflater.java

/** * Inflate a menu hierarchy from the specified XML resource. Throws {@link InflateException} if there is an error. * @param menuRes Resource ID for an XML layout resource to load (e.g.,<code>R.menu.main_activity</code>) * @param menu The Menu to inflate into. The items and submenus will beadded to this Menu. */ public void inflate(int menuRes,Menu menu){ XmlResourceParser parser=null; try { parser=mContext.getResources().getLayout(menuRes); AttributeSet attrs=Xml.asAttributeSet(parser); parseMenu(parser,attrs,menu); } catch ( XmlPullParserException e) { throw new InflateException("Error inflating menu XML",e); } catch ( IOException e) { throw new InflateException("Error inflating menu XML",e); } finally { if (parser != null) parser.close(); } }
Example 3
From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.
Source file: Webserver.java

/** * Read a line ended by CRLF, used internally only for reading headers. No char encoding, ASCII only */ protected String readLine(int maxLen) throws IOException { if (maxLen <= 0) throw new IllegalArgumentException("Max len:" + maxLen); StringBuffer buf=new StringBuffer(Math.min(1024,maxLen)); int c; boolean cr=false; int i=0; while ((c=in.read()) != -1) { if (c == 10) { if (cr) break; break; } else if (c == 13) cr=true; else { if (cr) throw new IOException("CR without LF"); cr=false; if (i >= maxLen) throw new IOException("Line lenght exceeds " + maxLen); buf.append((char)c); i++; } } if (STREAM_DEBUG) System.err.println(buf); if (c == -1 && buf.length() == 0) return null; return buf.toString(); }
Example 4
From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Commands/.
Source file: cmdSlots.java

private void setSlots(String[] args,CommandSender sender){ try { Integer maxPlayer=Integer.valueOf(args[0]); CraftServer server=(CraftServer)Bukkit.getServer(); server.getHandle().maxPlayers=maxPlayer; ChatUtils.writeSuccess(sender,"MaxPlayers set to " + maxPlayer + " !"); Properties p=new Properties(); BufferedReader bReader=new BufferedReader(new FileReader("server.properties")); p.load(bReader); bReader.close(); p.setProperty("max-players",maxPlayer.toString()); BufferedWriter bWriter=new BufferedWriter(new FileWriter("server.properties")); p.store(bWriter,""); bWriter.close(); } catch ( IOException IOE) { ConsoleUtils.printException(IOE,"Can't update server.properties!"); } catch ( NumberFormatException e) { ChatUtils.writeError(sender,args[0] + " is not a number!"); } }
Example 5
From project 2Degrees-Toolbox, under directory /Toolbox/src/biz/shadowservices/DegreesToolbox/.
Source file: HttpGetter.java

public String execute() throws ClientProtocolException, IOException { if (response == null) { HttpClient httpClient=HttpClientSingleton.getInstance(); HttpResponse serverresponse=null; serverresponse=httpClient.execute(httpget); HttpEntity entity=serverresponse.getEntity(); StringWriter writer=new StringWriter(); IOUtils.copy(entity.getContent(),writer); response=writer.toString(); } return response; }
Example 6
From project accent, under directory /src/main/java/net/lshift/accent/.
Source file: AccentChannel.java

/** * Add a listener that will be invoked each time the underlying channel is created or destroyed. Used mainly by the various messaging components that need to do work on channel setup, and cleanup on channel loss. * @param listener the callback that will be provided the channel. */ public void addChannelSetupListener(final ChannelListener listener){ synchronized (channelStateLock) { setupListeners.add(listener); } executeIfChannelValid(new ChannelCallback(){ public void runWithChannel( Channel c) throws IOException { listener.channelCreated(c); } } ); }
Example 7
From project accesointeligente, under directory /src/org/accesointeligente/server/.
Source file: GWTCacheControlFilter.java

public void doFilter(ServletRequest request,ServletResponse response,FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest=(HttpServletRequest)request; String requestURI=httpRequest.getRequestURI(); if (requestURI.contains(".nocache.")) { Date now=new Date(); HttpServletResponse httpResponse=(HttpServletResponse)response; httpResponse.setDateHeader("Date",now.getTime()); httpResponse.setDateHeader("Expires",now.getTime() - 86400000L); httpResponse.setHeader("Pragma","no-cache"); httpResponse.setHeader("Cache-control","no-cache, no-store, must-revalidate"); } filterChain.doFilter(request,response); }
Example 8
From project action-core, under directory /src/main/java/com/ning/metrics/action/binder/modules/.
Source file: FileSystemAccessProvider.java

@Inject public FileSystemAccessProvider(final ActionCoreConfig actionCoreConfig) throws IOException { final Configuration hadoopConfig=new Configuration(); final String hfsHost=actionCoreConfig.getNamenodeUrl(); if (hfsHost.isEmpty()) { hadoopConfig.set("fs.default.name","file:///"); } else { hadoopConfig.set("fs.default.name",hfsHost); } hadoopConfig.setInt("dfs.socket.timeout",actionCoreConfig.getHadoopSocketTimeOut()); hadoopConfig.setBoolean("fs.automatic.close",false); hadoopConfig.setLong("dfs.block.size",actionCoreConfig.getHadoopBlockSize()); hadoopConfig.set("hadoop.job.ugi",actionCoreConfig.getHadoopUgi()); hadoopConfig.setStrings("io.serializations",HadoopThriftWritableSerialization.class.getName(),HadoopThriftEnvelopeSerialization.class.getName(),HadoopSmileOutputStreamSerialization.class.getName(),"org.apache.hadoop.io.serializer.WritableSerialization",actionCoreConfig.getSerializations()); fileSystemAccess=new FileSystemAccess(hadoopConfig); }
Example 9
From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Commands/.
Source file: cmdRebuild.java

private boolean downloadSkin(String playerName){ int len1=0; InputStream is=null; OutputStream os=null; try { URL url=new URL("http://s3.amazonaws.com/MinecraftSkins/" + playerName + ".png"); is=url.openStream(); os=new FileOutputStream(new File(Core.getInstance().getDataFolder(),"/skins/" + playerName + ".png")); byte[] buff=new byte[4096]; while (-1 != (len1=is.read(buff))) { os.write(buff,0,len1); } os.flush(); } catch ( Exception ex) { return false; } finally { if (os != null) try { os.close(); } catch ( IOException ex) { } if (is != null) try { is.close(); } catch ( IOException ex) { } } return true; }
Example 10
From project 4308Cirrus, under directory /Extras/actionbarsherlock/src/com/actionbarsherlock/view/.
Source file: MenuInflater.java

/** * Inflate a menu hierarchy from the specified XML resource. Throws {@link InflateException} if there is an error. * @param menuRes Resource ID for an XML layout resource to load (e.g.,<code>R.menu.main_activity</code>) * @param menu The Menu to inflate into. The items and submenus will beadded to this Menu. */ public void inflate(int menuRes,Menu menu){ XmlResourceParser parser=null; try { parser=mContext.getResources().getLayout(menuRes); AttributeSet attrs=Xml.asAttributeSet(parser); parseMenu(parser,attrs,menu); } catch ( XmlPullParserException e) { throw new InflateException("Error inflating menu XML",e); } catch ( IOException e) { throw new InflateException("Error inflating menu XML",e); } finally { if (parser != null) parser.close(); } }
Example 11
From project 4308Cirrus, under directory /tendril-android-lib/src/test/java/edu/colorado/cs/cirrus/android/.
Source file: DeserializationTest.java

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

public static String getVersion(){ URL versionResource=Aardvark.class.getResource("/gw/vark/version.txt"); try { Reader reader=StreamUtil.getInputStreamReader(versionResource.openStream()); String version=StreamUtil.getContent(reader).trim(); return "Aardvark version " + version; } catch ( IOException e) { throw GosuExceptionUtil.forceThrow(e); } }
Example 13
From project Aardvark, under directory /aardvark-core/src/main/java/gw/vark/typeloader/.
Source file: AntlibTypeInfo.java

private static List<Pair<String,String>> readTaskListingFromPropertiesFile(String resourceName){ URL url=AntlibTypeLoader.class.getClassLoader().getResource(resourceName); InputStream in=null; try { in=url.openStream(); if (in == null) { AntlibTypeLoader.log("Could not load definitions from " + url,Project.MSG_WARN); } Properties tasks=new Properties(); tasks.load(in); List<Pair<String,String>> listing=new ArrayList<Pair<String,String>>(); for ( Map.Entry<Object,Object> entry : tasks.entrySet()) { listing.add(new Pair<String,String>((String)entry.getKey(),(String)entry.getValue())); } return listing; } catch ( IOException e) { throw GosuExceptionUtil.forceThrow(e); } finally { FileUtils.close(in); } }
Example 14
From project abalone-android, under directory /src/com/bytopia/abalone/.
Source file: GameActivity.java

@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 15
From project Absolute-Android-RSS, under directory /src/com/AA/Services/.
Source file: RssService.java

/** * Writes the received data to the application settings so that data restoration is easier * @param articleList - List of all the articles that have been aggregated from the stream */ public static void writeData(Context context,List<Article> articleList){ try { FileOutputStream fileStream=context.openFileOutput("articles",Context.MODE_PRIVATE); ObjectOutputStream writer=new ObjectOutputStream(fileStream); writer.writeObject(articleList); writer.close(); fileStream.close(); } catch ( IOException e) { Log.e("AARSS","Problem saving file.",e); return; } }
Example 16
From project Absolute-Android-RSS, under directory /src/com/AA/Services/.
Source file: RssService.java

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

/** * This can be used to launch the generation from a standalone application. * @param args Arguments of the generation. * @generated */ public static void main(String[] args){ try { if (args.length < 2) { System.out.println("Arguments not valid : {model, folder}."); } else { URI modelURI=URI.createFileURI(args[0]); File folder=new File(args[1]); List<String> arguments=new ArrayList<String>(); EcoreGenScala generator=new EcoreGenScala(modelURI,folder,arguments); for (int i=2; i < args.length; i++) { generator.addPropertiesFile(args[i]); } generator.doGenerate(new BasicMonitor()); } } catch ( IOException e) { e.printStackTrace(); } }
Example 18
From project acceleo-modules, under directory /psm-gen-scala/plugins/com.github.sbegaudeau.acceleo.modules.psm.gen.scala/src/com/github/sbegaudeau/acceleo/modules/psm/gen/scala/main/.
Source file: Workflow.java

/** * This can be used to launch the generation from a standalone application. * @param args Arguments of the generation. * @generated */ public static void main(String[] args){ try { if (args.length < 2) { System.out.println("Arguments not valid : {model, folder}."); } else { URI modelURI=URI.createFileURI(args[0]); File folder=new File(args[1]); List<String> arguments=new ArrayList<String>(); Workflow generator=new Workflow(modelURI,folder,arguments); for (int i=2; i < args.length; i++) { generator.addPropertiesFile(args[i]); } generator.doGenerate(new BasicMonitor()); } } catch ( IOException e) { e.printStackTrace(); } }
Example 19
From project acceleo-webapp-generator, under directory /plugins/org.eclipse.acceleo.tutorial/src/org/eclipse/acceleo/tutorial/wizard/.
Source file: EclipseConWizard.java

/** * Tries and find an encoding value on the very first line of the file contents. * @param fileContent The content from which to read an encoding value. * @return The charset name if it exists and is supported, <code>null</code> otherwise */ private static String getCharset(String fileContent){ String trimmedContent=fileContent.trim(); String charsetName=null; if (trimmedContent.length() > 0) { BufferedReader reader=new BufferedReader(new StringReader(trimmedContent)); String firstLine=trimmedContent; try { firstLine=reader.readLine(); } catch ( IOException e) { } Pattern encodingPattern=Pattern.compile("encoding\\s*=\\s*(\"|\')?([-a-zA-Z0-9]+)\1?"); Matcher matcher=encodingPattern.matcher(firstLine); if (matcher.find()) { charsetName=matcher.group(2); } } if (charsetName != null && Charset.isSupported(charsetName)) { return charsetName; } return null; }
Example 20
From project acceleo-webapp-generator, under directory /plugins/org.eclipse.acceleo.tutorial/src/org/eclipse/acceleo/tutorial/wizard/.
Source file: EclipseConWizard.java

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

/** * Closes the given accent channel. Any persist consumers will be terminated. * @throws IOException */ @Override public void close() throws IOException { this.connection.removeConnectionListener(this); executeIfChannelValid(new ChannelCallback(){ public void runWithChannel( Channel c) throws IOException { c.close(); channel=null; for ( ChannelListener cb : setupListeners) { cb.channelLost(); } } } ); }
Example 22
From project accesointeligente, under directory /src/org/accesointeligente/server/robots/.
Source file: ResponseChecker.java

private String htmlToString(String string) throws IOException { TagNode body; TagNode htmlDocument; string=string.replaceAll("<br/>","\n"); HtmlCleaner cleaner=new HtmlCleaner(); htmlDocument=cleaner.clean(string); body=(TagNode)htmlDocument.getElementsByName("body",true)[0]; String messageBody=body.getText().toString(); messageBody=messageBody.replaceAll(" "," "); messageBody=messageBody.replaceAll("[\t ]+"," "); messageBody=messageBody.trim(); messageBody=messageBody.replaceAll("(\n )","\n"); messageBody=messageBody.replaceAll("á","?"); messageBody=messageBody.replaceAll("Á","?"); messageBody=messageBody.replaceAll("é","?"); messageBody=messageBody.replaceAll("É","?"); messageBody=messageBody.replaceAll("í","?"); messageBody=messageBody.replaceAll("Í","?"); messageBody=messageBody.replaceAll("ó","?"); messageBody=messageBody.replaceAll("Ó","?"); messageBody=messageBody.replaceAll("ú","?"); messageBody=messageBody.replaceAll("Ú","?"); messageBody=messageBody.replaceAll("ñ","?"); messageBody=messageBody.replaceAll("Ñ","?"); return messageBody; }
Example 23
From project accounted4, under directory /accounted4/stock-quote/stock-quote-tmx/src/main/java/com/accounted4/stockquote/tmx/.
Source file: TmxOptionService.java

/** * Query the Montreal exchange for the option chain of a given symbol. Parse out the html response and return a chain object. * @param symbol * @return * @throws SAXException * @throws IOException */ public OptionChain getOptionChain(String symbol) throws SAXException, IOException { String urlString=BASE_URL.replaceAll("\\$\\{symbol\\}",symbol); System.out.println("Query url: " + urlString); HtmlSaxParser saxParser=new HtmlSaxParser(); TmxOptionPageHandler tmxOptionPageHandler=new TmxOptionPageHandler(symbol); saxParser.setContentHandler(tmxOptionPageHandler); saxParser.parse(urlString); return tmxOptionPageHandler.getOptionChain(); }
Example 24
From project accounted4, under directory /accounted4/stock-quote/stock-quote-tmx/src/main/java/com/accounted4/stockquote/tmx/.
Source file: TmxOptionService.java

/** * Give it a test run. * @param args * @throws SAXException * @throws IOException */ public static void main(String[] args) throws SAXException, IOException { TmxOptionService service=new TmxOptionService(); OptionChain optionChain=service.getOptionChain(args[0]); System.out.println("\n\n\n"); System.out.println(optionChain); }
Example 25
From project AceWiki, under directory /src/ch/uzh/ifi/attempto/aceeditor/.
Source file: ACEEditor.java

private void saveFile(){ final String f=getFullText(); AbstractDownloadProvider provider=new AbstractDownloadProvider(){ private static final long serialVersionUID=898782345234987345L; public String getContentType(){ return "text/plain"; } public String getFileName(){ return "text.ace.txt"; } public long getSize(){ return f.length(); } public void writeFile( OutputStream out) throws IOException { out.write(f.getBytes()); out.close(); } } ; getApplicationInstance().enqueueCommand(new DownloadCommand(provider)); }
Example 26
From project AceWiki, under directory /src/ch/uzh/ifi/attempto/aceeditor/.
Source file: ACEEditor.java

private void saveLexicon(){ final String f=lexiconHandler.getLexiconFileContent(); AbstractDownloadProvider provider=new AbstractDownloadProvider(){ private static final long serialVersionUID=1932606314346272768L; public String getContentType(){ return "text/plain"; } public String getFileName(){ return "text.lex.pl"; } public long getSize(){ return f.length(); } public void writeFile( OutputStream out) throws IOException { out.write(f.getBytes()); out.close(); } } ; getApplicationInstance().enqueueCommand(new DownloadCommand(provider)); }
Example 27
From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/config/.
Source file: JsonConfigLoader.java

/** * Read the configuration from an input stream * @param configFile * @return the configuration or null if there was a problem reading. * @throws ConfigurationException */ public C readConfiguration(InputStream is) throws ConfigurationException { try { ObjectMapper mapper=new ObjectMapper(); C res=mapper.readValue(is,clazz); return res; } catch ( JsonParseException ex) { throw new ConfigurationException("The input is not valid JSON",ex); } catch ( JsonMappingException ex) { throw new ConfigurationException("The input JSON doesn't match " + "the " + clazz.getCanonicalName() + " class",ex); } catch ( IOException ex) { throw new ConfigurationException("IO error while reading the JSON",ex); } }
Example 28
From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/config/.
Source file: JsonConfigLoader.java

/** * Load the configuration from a file. * @param configFile * @return the configuration or null if it couldn't be found / read. * @throws ConfigurationException */ public C loadConfiguration(String configFile) throws ConfigurationException { InputStream is=null; try { File cf=new File(configFile == null ? "config.json" : configFile); is=new FileInputStream(cf); return readConfiguration(is); } catch ( IOException ex) { throw new ConfigurationException("Cannot open file '" + configFile + "'",ex); } finally { closeQuietly(is); } }
Example 29
From project action-core, under directory /src/main/java/com/ning/metrics/action/endpoint/.
Source file: HdfsBrowser.java

/** * Build a Viewable to browse HDFS. * @param path path in HDFS to render (directory listing or file), defaults to / * @param raw optional, whether to try to deserialize * @param recursive optional, whether to crawl all files under a directory * @return Viewable to render the jsp * @throws IOException HDFS crawling error */ @GET @Path("/hdfs") @Produces({"text/html","text/plain"}) @Timed public Viewable getListing(@QueryParam("path") String path,@QueryParam("raw") final boolean raw,@QueryParam("recursive") final boolean recursive) throws IOException { log.debug(String.format("Got request for path=[%s], raw=[%s] and recursive=[%s]",path,raw,recursive)); if (path == null) { path="/"; } if (hdfsReader.isDir(path) && !recursive) { return new Viewable("/rest/listing.jsp",hdfsReader.getListing(path)); } else { if (raw) { return new Viewable("/rest/contentRaw.jsp",hdfsReader.getListing(path,raw,recursive)); } else { return new Viewable("/rest/content.jsp",hdfsReader.getListing(path,raw,recursive)); } } }