/** * Runs the test using the specified harness. * * @param harness the test harness (<code>null</code> not permitted). */ public void test(TestHarness harness) { FileNotFoundException object1 = new FileNotFoundException(); harness.check(object1 != null); harness.check(object1.toString(), "java.io.FileNotFoundException"); FileNotFoundException object2 = new FileNotFoundException("nothing happens"); harness.check(object2 != null); harness.check(object2.toString(), "java.io.FileNotFoundException: nothing happens"); FileNotFoundException object3 = new FileNotFoundException(null); harness.check(object3 != null); harness.check(object3.toString(), "java.io.FileNotFoundException"); }
public static void main(String[] args) { try { InferenceGraph G = new InferenceGraph("hw5.bif"); Vector nodes = G.get_nodes(); InferenceGraphNode n = ((InferenceGraphNode) nodes.elementAt(0)); System.out.println(n.get_name()); n.get_Prob().print(); // Create string of variable-value pairs for probability table at node 0*/ String[][] s = new String[1][2]; s[0][0] = "B"; s[0][1] = "False"; // Compute probability with given variable-value pairs; System.out.println(n.get_function_value(s)); Vector children = n.get_children(); // get_parents() works too; for (Enumeration e = children.elements(); e.hasMoreElements(); ) { InferenceGraphNode no = (InferenceGraphNode) (e.nextElement()); System.out.println("\t" + no.get_name()); no.get_Prob().print(); // Get the probability table object for the node -> Look at // ProbabilityFunction.java for info } } catch (IFException e) { System.out.println("Formatting Incorrect " + e.toString()); } catch (FileNotFoundException e) { System.out.println("File not found " + e.toString()); } catch (IOException e) { System.out.println("File not found " + e.toString()); } }
MyX509TrustManager() throws java.security.GeneralSecurityException { TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX"); KeyStore ks = KeyStore.getInstance("JKS"); CertificateFactory cf = CertificateFactory.getInstance("X.509"); try { ks.load(null, null); File cacert = new File(cafile); if (!cacert.exists() || !cacert.canRead()) return; InputStream caStream = new FileInputStream(cafile); X509Certificate ca = (X509Certificate) cf.generateCertificate(caStream); ks.setCertificateEntry("CA", ca); PKIXBuilderParameters params = new PKIXBuilderParameters(ks, new X509CertSelector()); File crlcert = new File(crlfile); if (!crlcert.exists() || !crlcert.canRead()) { params.setRevocationEnabled(false); } else { InputStream crlStream = new FileInputStream(crlfile); Collection<? extends CRL> crls = cf.generateCRLs(crlStream); CertStoreParameters csp = new CollectionCertStoreParameters(crls); CertStore store = CertStore.getInstance("Collection", csp); params.addCertStore(store); params.setRevocationEnabled(true); } tmf.init(new CertPathTrustManagerParameters(params)); } catch (java.io.FileNotFoundException e) { vlog.error(e.toString()); } catch (java.io.IOException e) { vlog.error(e.toString()); } tm = (X509TrustManager) tmf.getTrustManagers()[0]; }
public static void main(String[] args) { try { Scanner scanner = new Scanner(new FileInputStream("graph.txt")); int v = Integer.parseInt(scanner.nextLine()); int source = Integer.parseInt(scanner.nextLine()); int sink = Integer.parseInt(scanner.nextLine()); ListGraph g = new ListGraph(v, source, sink); while (scanner.hasNext()) { String edgeLine = scanner.nextLine(); String[] components = edgeLine.split("\\s+"); assert components.length == 3; int i = Integer.parseInt(components[0]); int j = Integer.parseInt(components[1]); int capacity = Integer.parseInt(components[2]); g.addEdge(i, j, capacity); } System.out.println("Original matrix"); g.print(); ListGraph.maxFlow(g); g.print(); } catch (FileNotFoundException e) { System.err.println(e.toString()); System.exit(1); } }
/** * Saves the given Bitmap in the specified path. The Bitmap is stored using the PNG format. * * @param fileName name that the file will have * @param bitmap Bitmap to save as a file. * @return returns true if the file was saved successfully. */ public Boolean saveImage(String fileName, Bitmap bitmap) { OutputStream outStream = null; File file = new File(mExternalDirectoryPath, fileName); // removes any previously existing file with the same name if (file.exists()) { file.delete(); } try { outStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 50, outStream); outStream.flush(); outStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); Toast.makeText(MapCrawler.this, e.toString(), Toast.LENGTH_LONG).show(); return false; } catch (IOException e) { e.printStackTrace(); Toast.makeText(MapCrawler.this, e.toString(), Toast.LENGTH_LONG).show(); return false; } return true; }
private String readFromFile() { String ret = ""; try { InputStream inputStream = openFileInput(newfile); if (inputStream != null) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String receiveString = ""; StringBuilder stringBuilder = new StringBuilder(); while ((receiveString = bufferedReader.readLine()) != null) { stringBuilder.append(receiveString); } inputStream.close(); ret = stringBuilder.toString(); } else { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); } } catch (FileNotFoundException e) { Log.e("login activity", "File not found: " + e.toString()); } catch (IOException e) { Log.e("login activity", "Can not read file: " + e.toString()); } return ret; }
public String dbPreCreatedDisplay() { // TODO Auto-generated method stub String para = ""; DBAdapterPreDB db = new DBAdapterPreDB(context); try { String destPath = "/data/data/" + Package_name + "/databases"; File f = new File(destPath); if (!f.exists()) { f.mkdirs(); f.createNewFile(); // ---copy the db from the assets folder into // the databases folder--- CopyDB(context.getAssets().open("mydb"), new FileOutputStream(destPath + "/MyDB")); } } catch (FileNotFoundException e) { Toast.makeText(context, "Error 401: Db copy: " + e.toString(), Toast.LENGTH_LONG).show(); } catch (IOException e) { Toast.makeText(context, "Error 402: Db copy: " + e.toString(), Toast.LENGTH_LONG).show(); } // ---get all contacts--- db.open(); Cursor c = db.getAllContacts(); if (c.moveToFirst()) { do { para += DisplayContact(c); } while (c.moveToNext()); } db.close(); return para; }
public static String CreateZip(String[] filesToZip, String zipFileName) { byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); out.setLevel(Deflater.BEST_COMPRESSION); for (int i = 0; i < filesToZip.length; i++) { FileInputStream in = new FileInputStream(filesToZip[i]); String fileName = null; for (int X = filesToZip[i].length() - 1; X >= 0; X--) { if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') { fileName = filesToZip[i].substring(X + 1); break; } else if (X == 0) fileName = filesToZip[i]; } out.putNextEntry(new ZipEntry(fileName)); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); } out.close(); } catch (IllegalArgumentException e) { return "Failed to create zip: " + e.toString(); } catch (FileNotFoundException e) { return "Failed to create zip: " + e.toString(); } catch (IOException e) { return "Failed to create zip: " + e.toString(); } return "Success"; }
/** 存储到props文件的格式中 */ public void storeToProps() { FileOutputStream fos = null; try { fos = new FileOutputStream(configFile); } catch (FileNotFoundException e1) { System.out.println("文件未找到:" + configFile + e1.toString()); } try { conf.store(fos, ""); } catch (FileNotFoundException e) { System.err.println("配置文件" + configFile + "找不到!!\n" + e.toString()); } catch (Exception e) { System.err.println("读取配置文件" + configFile + "错误!!\n" + e.toString()); } }
@Override public boolean onCreateOptionsMenu(Menu menu) { // Build from this.menuItems if (this.menuItems.length > 0) { for (int i = 0; i < this.menuItems.length; i++) { // menu.add(this.menuItems[i].groupid, this.menuItems[i].id, order, // this.menuItems[i].title); MenuItem item = menu.add(0, menuItems[i].id, i, menuItems[i].title); // Add icon try { // TODO: handle standard icons i.e. item.setIcon(android.R.drawable.ic_menu_preferences) item.setIcon( new BitmapDrawable(this.getResources(), this.getAssets().open(menuItems[i].icon))); } catch (java.io.FileNotFoundException e) { Log.d(LOG_TAG, e.toString()); } catch (java.io.IOException e) { Log.d(LOG_TAG, e.toString()); throw new RuntimeException(e); } } return true; } return false; }
public void downloadfile(File file) { boolean uploadResult; File getfile = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), file.getName()); ; Log.e("FTP", "파일정보 : " + getfile.getPath() + "경로 : " + getfile.getAbsolutePath()); try { outputstream = new FileOutputStream(getfile); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block Log.e("FTP_SEND_ERR", "outputstream 생성 실패" + e1.toString()); e1.printStackTrace(); } try { FTPConnector.ftp.setFileType(FTP.BINARY_FILE_TYPE); uploadResult = FTPConnector.ftp.retrieveFile(file.getName(), outputstream); if (!uploadResult) { Log.e("FTP_SEND_ERR", "파일 전송을 실패하였습니다."); uploadResult = false; handler.post(failmsg); } } catch (IOException e) { // TODO Auto-generated catch block Log.e("FTP_SEND_ERR", "파일 전송에 문제가 생겼습니다." + e.toString()); uploadResult = false; handler.post(failmsg); } }
@Test public void checkFile() { FileReader fr = null; try { File exerciseFile = new File(FILENAME); assertTrue(exerciseFile.exists()); fr = new FileReader(exerciseFile); BufferedReader br = new BufferedReader(fr); List<String> lines = new ArrayList<String>(); String line; while ((line = br.readLine()) != null) { lines.add(line); } assertEquals(5, lines.size()); } catch (FileNotFoundException ex) { fail("File not found: " + ex.toString()); } catch (IOException ex) { fail("IO exception: " + ex.toString()); } finally { try { fr.close(); } catch (IOException ex) { fail("Error closing: " + ex.toString()); } } }
public static List<String> readFile(String filePath) { List<String> lines = new ArrayList<>(); BufferedReader br = null; String line = null; try { br = new BufferedReader(new FileReader(filePath)); while ((line = br.readLine()) != null) { lines.add(line); } return lines; } catch (FileNotFoundException e) { System.out.println("File cannot be loaded! " + e.toString()); } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } return lines; }
private NodeList load() throws IOException, FileNotFoundException, ParserConfigurationException, SAXException, TransformerException { InputStream fis = null; NodeList nl = null; try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); fis = new FileInputStream(fileName); nl = XPathAPI.selectNodeList(builder.parse(fis), xpath); log.debug("found " + nl.getLength()); } catch (FileNotFoundException e) { log.warn(e.toString()); throw e; } catch (IOException e) { log.warn(e.toString()); throw e; } catch (ParserConfigurationException e) { log.warn(e.toString()); throw e; } catch (SAXException e) { log.warn(e.toString()); throw e; } catch (TransformerException e) { log.warn(e.toString()); throw e; } finally { JOrphanUtils.closeQuietly(fis); } return nl; }
public void run(String fileName) { this.fileName = fileName; tree = new TreeSet<Range>(new RangeComparator()); try { BufferedReader bis = new BufferedReader(new FileReader(fileName)); String line; while ((line = bis.readLine()) != null) { processLine(line); } System.out.println("-----"); for (Range r : tree) { System.out.println(r.toString()); } } catch (FileNotFoundException ex) { System.err.println(ex.toString()); } catch (IOException ex) { System.err.println(ex.toString()); } }
/** * Decodes and scales a contact's image from a file pointed to by a Uri in the contact's data, and * returns the result as a Bitmap. The column that contains the Uri varies according to the * platform version. * * @param photoData provide the Contact.PHOTO_THUMBNAIL_URI value. * @param imageSize The desired target width and height of the output image in pixels. * @return A Bitmap containing the contact's image, resized to fit the provided image size. If no * thumbnail exists, returns null. */ private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) { // Ensures the Fragment is still added to an activity. As this method is called in a // background thread, there's the possibility the Fragment is no longer attached and // added to an activity. If so, no need to spend resources loading the contact photo. if (!isAdded() || getActivity() == null) { return null; } // Instantiates an AssetFileDescriptor. Given a content Uri pointing to an image file, the // ContentResolver // can return an AssetFileDescriptor for the file. AssetFileDescriptor afd = null; // This "try" block catches an Exception if the file descriptor returned from the Contacts // Provider doesn't point to an existing file. try { Uri thumbUri; // Converts the Uri passed as a string to a Uri object. thumbUri = Uri.parse(photoData); // Retrieves a file descriptor from the Contacts Provider. To learn more about this // feature, read the reference documentation for // ContentResolver#openAssetFileDescriptor. afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r"); // Gets a FileDescriptor from the AssetFileDescriptor. A BitmapFactory object can // decode the contents of a file pointed to by a FileDescriptor into a Bitmap. FileDescriptor fileDescriptor = afd.getFileDescriptor(); if (fileDescriptor != null) { // Decodes a Bitmap from the image pointed to by the FileDescriptor, and scales it // to the specified width and height return ImageLoader.decodeSampledBitmapFromDescriptor(fileDescriptor, imageSize, imageSize); } } catch (FileNotFoundException e) { // If the file pointed to by the thumbnail URI doesn't exist, or the file can't be // opened in "read" mode, ContentResolver.openAssetFileDescriptor throws a // FileNotFoundException. if (BuildConfig.DEBUG) { Log.d( TAG, "Contact photo thumbnail not found for contact " + photoData + ": " + e.toString()); } } finally { // If an AssetFileDescriptor was returned, try to close it if (afd != null) { try { afd.close(); } catch (IOException e) { // Closing a file descriptor might cause an IOException if the file is // already closed. Nothing extra is needed to handle this. } } } // If the decoding failed, returns null return null; }
public void refresh() { final File f = new File(MEMINFO_FILE); try (Scanner scanner = new Scanner(f, "UTF-8")) { parseFromScanner(scanner); } catch (final FileNotFoundException ex) { throw new RuntimeException("File " + MEMINFO_FILE + " not found:" + ex.toString()); } }
/** * get the raw "payload" of a frame that encapsulates an external type such as an APIC frame. this * is defined as the frame itself by default. * * @return */ @Override public byte[] getPayload() throws IOException { byte[] payload = null; try { payload = reload(); } catch (FileNotFoundException ex) { this.log(Level.WARNING, "file not found retrieving payload " + ex.toString()); } return payload; }
@Test public void testSingleParsing() { try { RpmSpecParser parser = RpmSpecParser.createParser("src/test/resources/specs/p4bugzilla.spec"); assertNotNull(parser); checkP4BugzillaResults(toProperties(parser.parse())); } catch (FileNotFoundException e) { fail(e.toString()); } }
/** * Load a file * * @param file the file to load * @return the model element * @throws JAXBException on error */ @SuppressWarnings("unchecked") public Model load(File file) throws JAXBException { InputStreamReader reader; try { reader = new InputStreamReader(new FileInputStream(file), Charset.forName(LATIN1_ENCODING)); } catch (FileNotFoundException e) { Logger.getLogger(Modelica.class.getName()).severe(e.toString()); return null; } return ((JAXBElement<Model>) unmarshaller.unmarshal(reader)).getValue(); }
Master(File _file, Name defaultOrigin) throws IOException { FileInputStream fis; file = _file; try { fis = new FileInputStream(file); } catch (FileNotFoundException e) { throw new IOException(e.toString()); } br = new BufferedReader(new InputStreamReader(fis)); origin = defaultOrigin; }
// enable user to open file private void openFile() { try { input = new Scanner(new File("cartaoCredito.txt")); } // end try catch (FileNotFoundException fileNotFoundException) { System.err.println("Error opening file."); System.out.println(fileNotFoundException.toString()); System.out.println(fileNotFoundException.getMessage()); System.exit(1); } // end catch } // end method openFile
protected InputStream createTestBundleWithProcessDefinition() { try { return TinyBundles.bundle() .add( "OSGI-INF/activiti/example.bpmn20.xml", new FileInputStream(new File("src/test/resources/processes/example.bpmn20.xml"))) .set(Constants.BUNDLE_SYMBOLICNAME, "org.activiti.osgi.example") .build(); } catch (FileNotFoundException fnfe) { fail("Failure in createTestBundleWithProcessDefinition " + fnfe.toString()); return null; } }
// utility method to get a Bitmap from a Uri public Bitmap getBitmap(Uri uri, ContentResolver cr, BitmapFactory.Options options) { Bitmap bitmap = null; // get the image try { InputStream input = cr.openInputStream(uri); bitmap = BitmapFactory.decodeStream(input, null, options); } // end try catch (FileNotFoundException e) { Log.v(TAG, e.toString()); } // end catch return bitmap; } // end method getBitmap
protected InputStream createTestBundleWithProcessEngineConfiguration() { try { return TinyBundles.bundle() .add( "OSGI-INF/blueprint/context.xml", new FileInputStream(new File("src/test/resources/config/context.xml"))) .set(Constants.BUNDLE_SYMBOLICNAME, "org.activiti.osgi.config") .set(Constants.DYNAMICIMPORT_PACKAGE, "*") .build(); } catch (FileNotFoundException fnfe) { fail("Failure in createTestBundleWithProcessEngineConfiguration " + fnfe.toString()); return null; } }
public Lexer(String fileName) { this.fileName = fileName; FileReader filereader = null; try { filereader = new FileReader(fileName); } catch (FileNotFoundException fnfe) { System.out.println("Create FileReader from file " + fileName + "failed: " + fnfe.toString()); } reader = new LineNumberReader(filereader); line = null; lineNo = 0; lineOffset = 0; }
/** @param dictname */ public StarDict(String dictname) { try { this.dictname = dictname; this.index = new RandomAccessFile(dictname + ".idx", "r"); this.dz = new DictZipFile(dictname + ".dz"); this.yaindex = new RandomAccessFile(dictname + ".yaidx", "r"); // this.dz.runtest(); } catch (FileNotFoundException e) { last_error = e.toString(); e.printStackTrace(); } catch (Exception e) { last_error = e.toString(); e.printStackTrace(); } }
public FileOps() { JFileChooser choose = new JFileChooser("."); int status = choose.showOpenDialog(null); try { if (status != JFileChooser.APPROVE_OPTION) throw new IOException(); f = choose.getSelectedFile(); if (!f.exists()) throw new FileNotFoundException(); } catch (FileNotFoundException e) { display(e.toString(), "File not found ...."); } catch (IOException e) { display(e.toString(), "Approve option was not selected"); } }
/** * Load the properties from the XML file specified. * * @param propFile the properties file. */ private void loadProp(String propFile) { VMprop = new Properties(); try { logger.section("Loading VM test case properties..."); VMpropFile = propFile; FileInputStream in = new FileInputStream(VMpropFile); VMprop.loadFromXML(in); in.close(); } catch (FileNotFoundException ex) { logger.fatal(ex.toString()); } catch (InvalidPropertiesFormatException ex) { logger.fatal(ex.toString()); } catch (IOException ex) { logger.fatal(ex.toString()); } }
private static void startServer() { try { if (!FileUtils.isFileLocked(serverFile.getAbsolutePath())) { JpaNetworkServer networkServer = new JpaNetworkServer(); networkServer.startServer(serverFile.getAbsolutePath(), port, password); Arrays.fill(password, (char) 0); // clear the password to protect against malicious code } else { System.err.println(ResourceUtils.getString("Message.FileIsLocked")); } } catch (final FileNotFoundException e) { Logger.getLogger(jGnashFx.class.getName()).log(Level.SEVERE, e.toString(), e); System.err.println("File " + serverFile.getAbsolutePath() + " was not found"); } catch (final Exception e) { Logger.getLogger(jGnashFx.class.getName()).log(Level.SEVERE, e.toString(), e); } }