private static void testSysOut(String fs, String exp, Object... args) { FileOutputStream fos = null; FileInputStream fis = null; try { PrintStream saveOut = System.out; fos = new FileOutputStream("testSysOut"); System.setOut(new PrintStream(fos)); System.out.format(Locale.US, fs, args); fos.close(); fis = new FileInputStream("testSysOut"); byte[] ba = new byte[exp.length()]; int len = fis.read(ba); String got = new String(ba); if (len != ba.length) fail(fs, exp, got); ck(fs, exp, got); System.setOut(saveOut); } catch (FileNotFoundException ex) { fail(fs, ex.getClass()); } catch (IOException ex) { fail(fs, ex.getClass()); } finally { try { if (fos != null) fos.close(); if (fis != null) fis.close(); } catch (IOException ex) { fail(fs, ex.getClass()); } } }
public static void main(String[] args) { long st, dt, et; String plaintext1 = "Yellow and Black Border Collies"; String keysPath = "keys.txt"; RSA rsa; try { Scanner in = new Scanner(new FileReader(keysPath)); BigInteger n = new BigInteger(in.nextLine().substring(3)); BigInteger e = new BigInteger(in.nextLine().substring(3)); BigInteger d = new BigInteger(in.nextLine().substring(3)); in.close(); rsa = new RSA(n, e, d); } catch (FileNotFoundException e) { e.printStackTrace(); return; } // rsa = new RSA(8, 1024); st = System.currentTimeMillis(); String ciphertext = rsa.encrypt(plaintext1); dt = System.currentTimeMillis(); String plaintext2 = rsa.decrypt(ciphertext); et = System.currentTimeMillis(); System.out.println("enc time: " + (dt - st)); System.out.println("dec time: " + (et - dt)); System.out.println(plaintext2); // rsa.saveKeys(keysPath); }
public static String readFile(File file) { FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; StringBuilder br = new StringBuilder(); try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); while (dis.available() != 0) { br.append(dis.readLine() + "\n"); } // dispose all the resources after using them. fis.close(); bis.close(); dis.close(); return br.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new String(); }
private void writeAudioDataToFile() { byte data[] = new byte[bufferSize]; String filename = getTempFilename(); FileOutputStream os = null; try { os = new FileOutputStream(filename); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Log.d("SAN", e.getMessage()); } int read = 0; if (null != os) { while (isRecording) { read = recorder.read(data, 0, bufferSize); if (AudioRecord.ERROR_INVALID_OPERATION != read) { try { os.write(data); } catch (IOException e) { Log.d("SAN", e.getMessage()); } } } try { os.close(); } catch (IOException e) { Log.d("SAN", e.getMessage()); } } }
/** * Retrieve a list of name-script key-value pairs. * * @return */ public final Map<String, String> loadScripts() { HashMap<String, String> scripts = new HashMap<String, String>(); try { URL url = this.getClass().getClassLoader().getResource(this.directory); if (url == null) { throw new RuntimeException("The following directory was not found: " + this.directory); } URI uri = new URI(url.toString()); File directory = new File(uri); FilenameFilter filter = new JavascriptFilter(); for (String file : directory.list(filter)) { String script = this.readScript(directory, file); int dotIndex = file.lastIndexOf('.'); scripts.put(file.substring(0, dotIndex), script.toString()); } } catch (URISyntaxException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } return scripts; }
public void processFile(String inputFileName) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(inputFileName)))); String[] headers = reader.readLine().split(SEPARATOR); for (String s : headers) { attrByValue.put(s, new HashSet<String>()); } String line = null; while ((line = reader.readLine()) != null) { String[] columnValues = line.split(SEPARATOR); if (columnValues.length != headers.length) { System.err.println("There is a huge problem with data file"); } for (int i = 0; i < columnValues.length; i++) { attrByValue.get(headers[i]).add(columnValues[i]); } } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@SuppressWarnings("resource") public FileInfo upload(String name) { String filepath = "/Users/JIANG/Documents/workspace/P8/P8"; String uploadFile = filepath + "/" + name; System.out.println(uploadFile); FileInfo fi = new FileInfoImplem(); BufferedInputStream input = null; File file = new File(uploadFile); byte[] content = new byte[(int) file.length()]; try { input = new BufferedInputStream(new FileInputStream(file)); System.out.println(input.read(content)); input.read(content); fi.setFileInfo(name, content); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } input = null; } } return fi; }
public Card readCard(File filePath) { Card card = null; try { FileInputStream fis = new FileInputStream(filePath); ObjectInputStream ois = new ObjectInputStream(fis); card = (Card) ois.readObject(); System.out.println( "Card " + card.getName() + " converted mana cost " + card.getConvertedManacost()); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return card; }
public static void resetConfig() { try { menuProps.setProperty("selectedMenu", ""); menuProps.setProperty("loopMusic", "true"); menuProps.setProperty("muteMusic", "false"); menuProps.setProperty("lastMusicIndex", String.valueOf(jukebox.getIndexFromName("Strad"))); menuProps.setProperty("musicIndex", String.valueOf(jukebox.getIndexFromName("Strad"))); menuProps.setProperty("musicSet", "false"); menuProps.setProperty("hasPlayedMusic", "false"); menuProps.setProperty("hasStartedMusic", "false"); Minecraft.getMinecraft(); menuProps.store( new FileOutputStream(Minecraft.getMinecraftDir() + "/MenuAPI.properties"), null); Minecraft.getMinecraft(); FileInputStream in = new FileInputStream(Minecraft.getMinecraftDir() + "/MenuAPI.properties"); menuProps.load(in); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static void loadConfig() { if (config.exists()) try { Minecraft.getMinecraft(); FileInputStream in = new FileInputStream(Minecraft.getMinecraftDir() + "/MenuAPI.properties"); menuProps.load(in); if (menuProps.size() <= 0) { resetConfig(); return; } selectedMenuName = String.valueOf(menuProps.getProperty("selectedMenu")); loopMusic = menuProps.getProperty("loopMusic").equals("true"); muteMusic = menuProps.getProperty("muteMusic").equals("true"); lastMusicIndex = Integer.valueOf(menuProps.getProperty("lastMusicIndex")).intValue(); musicIndex = Integer.valueOf(menuProps.getProperty("musicIndex")).intValue(); musicSet = menuProps.getProperty("musicSet").equals("true"); hasPlayedMusic = menuProps.getProperty("hasPlayedMusic").equals("true"); hasStartedMusic = menuProps.getProperty("hasStartedMusic").equals("true"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } else resetConfig(); }
/** @param args */ public static void main(String[] args) { // TODO Auto-generated method stub PrefixTree tree = new PrefixTree(); try { BufferedReader reader = new BufferedReader(new FileReader("company code.txt")); String line = reader.readLine(); while (line != null) { StringTokenizer tokenizer = new StringTokenizer(line); String code = tokenizer.nextToken(); tree.insert(code.toLowerCase() + "$"); line = reader.readLine(); } ArrayList<String> result = tree.search_prefix("a"); for (int i = 0; i < result.size(); i++) { System.out.println(result.get(i)); } reader.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } }
@Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(CANCELAR)) { PPal.get().seleccionarPrimerFactura(); } else if (e.getActionCommand().equals(CONFIRMAR)) { PPal.get().agregarFactura(getNewFactura()); } else if (e.getActionCommand().equals(CARGAR)) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { txtBono.setText(ManagerQR.readQRCode(chooser.getSelectedFile())); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (NotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }
public static void main(String[] args) { BufferedReader in; try { in = new BufferedReader( new FileReader( "/Users/rahulkhairwar/Documents/IntelliJ IDEA Workspace/Competitive " + "Programming/src/com/google/codejam16/qualificationround/inputB.txt")); OutputWriter out = new OutputWriter(System.out); Thread thread = new Thread(null, new Solver(in, out), "Solver", 1 << 28); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } out.flush(); in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * Constructs a matrix from the given file, assuming that it is csv. * * @throws IOException */ public Matrix(String filename, int height, int width) throws IOException { this.mat = new double[height][width]; BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); } catch (FileNotFoundException e) { e.printStackTrace(); } if (reader == null) { // bad stuff.... return; } String matrix = reader.readLine(); String[] strMat = matrix.split(",", 0); int index = 0; for (int i = 0; i < height; i++) { index = i * width; for (int j = 0; j < width; j++) { mat[i][j] = Double.parseDouble(strMat[index + j]); } } }
// 处理歌词文件 public void readLRC(String path) { File file = new File(path); try { FileInputStream fileInputStream = new FileInputStream(file); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "gbk"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String s = ""; while ((s = bufferedReader.readLine()) != null) { addTimeToList(s); // Log.i(TAG, s); if ((s.indexOf("[ar:") != -1) || (s.indexOf("[ti:") != -1) || (s.indexOf("[by:") != -1) || (s.indexOf("[al:") != -1) || (s.indexOf("[offset:") != -1)) { s = s.substring(s.indexOf(":") + 1, s.indexOf("]")); } else { String ss = s.substring(s.indexOf("["), s.indexOf("]") + 1); s = s.replace(ss, ""); } mWords.add(s); } bufferedReader.close(); inputStreamReader.close(); fileInputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); mWords.add("没有歌词文件,赶紧去下载"); } catch (IOException e) { e.printStackTrace(); mWords.add("没有读取到歌词"); } }
// Load stored ToDoItems private void loadItems() { BufferedReader reader = null; try { FileInputStream fis = openFileInput(FILE_NAME); reader = new BufferedReader(new InputStreamReader(fis)); String title = null; String priority = null; String status = null; Date date = null; while (null != (title = reader.readLine())) { priority = reader.readLine(); status = reader.readLine(); date = ToDoItem.FORMAT.parse(reader.readLine()); mAdapter.add(new ToDoItem(title, Priority.valueOf(priority), Status.valueOf(status), date)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } finally { if (null != reader) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public void saveCard(String filePath, Card card) { File file = new File(filePath); if (!file.exists()) { try { file.createNewFile(); System.out.println("File " + file.getName() + " was created."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { FileOutputStream fos = new FileOutputStream(filePath); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(card); fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } }
public static void main(String[] args) { try { Scanner consoleInput = new Scanner(System.in); System.out.println("Enter file name: "); String fileName = consoleInput.next(); if (!fileName.endsWith(".t")) { System.out.println("Expecting a LOGO file"); return; } Root program = Parser.parse(Lexer.tokenise(FileManager.contentsOfFile(fileName))); System.out.println("Enter output file name"); String outFileName = consoleInput.next(); if (!outFileName.endsWith(".ps") && !outFileName.endsWith(".eps")) { outFileName += ".ps"; } String output = CodeGenerator.generateCodeText(program); if (ErrorLog.containsErrors()) { ErrorLog.displayErrors(); return; } else { FileManager.writeStringToFile(output, outFileName); } } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (IOException IO) { System.out.println(IO.getMessage()); } }
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"; }
/** * Decode and sample down a bitmap from a file to the requested width and height. * * @param filename The full path of the file to decode * @param reqWidth The requested width of the resulting bitmap * @param reqHeight The requested height of the resulting bitmap * @param cache The ImageCache used to find candidate bitmaps for use with inBitmap * @return A bitmap sampled down from the original with the same aspect ratio and dimensions that * are equal to or greater than the requested width and height */ public static Bitmap decodeSampledBitmapFromUri( Context context, Uri fileuri, int reqWidth, int reqHeight, ImageCache cache) { Bitmap bm = null; try { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream( context.getContentResolver().openInputStream(fileuri), null, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; bm = BitmapFactory.decodeStream( context.getContentResolver().openInputStream(fileuri), null, options); } catch (FileNotFoundException e) { e.printStackTrace(); } return bm; }
public static void writeFile() { try { // if region data is saved read from it otherwise create a new one. read("regions"); // copy data from file to a new object RegionHandling.setRegions(); } catch (FileNotFoundException e) { // if file was not found, attempt to create a new one Main.sendDebugInfo("Can't find region data file. Attepting to create a new one"); try { // attempt to write regions object to file save("regions"); Main.sendDebugInfo("New region data file created successfully!"); } catch (FileNotFoundException e1) { // if FileNotFoundException send error msg to console Main.sendSevereInfo( "A problem occurred attempting to read from the region data file : FileNotFoundException"); e1.printStackTrace(); } } }
public ArrayList<Brick> getBricks(String fileName) { try { Scanner in = new Scanner(new File(fileName)); ArrayList<String> lines = new ArrayList<>(); while (in.hasNextLine()) { lines.add(in.nextLine()); } in.close(); char[][] chars = new char[lines.size()][]; for (int i = 0; i < lines.size(); i++) { chars[i] = lines.get(i).toCharArray(); } ArrayList<Brick> ret = new ArrayList<>(); int width = 70, height = 40; for (int r = 0; r < chars.length; r++) { for (int c = 0; c < chars[r].length; c++) { if (chars[r][c] != ' ') { int x = c * width; int y = r * height; ret.add(new Brick(x, y, width, height)); } } } return ret; } catch (FileNotFoundException e) { e.printStackTrace(); return null; } }
/* * recovery a class from path's file */ @SuppressWarnings("finally") public Object readSerializableData(String path) { Object yyc = null; try { FileInputStream fis = new FileInputStream(path); ObjectInputStream ois = new ObjectInputStream(fis); yyc = (Object) ois.readObject(); ois.close(); return yyc; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (StreamCorruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { return yyc; } }
public ArrayList getWordListFromFile() { JFileChooser openFileChooser = new JFileChooser(); openFileChooser.setDialogTitle("Select a word list file"); ArrayList allWords = new ArrayList(); if (openFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { BufferedReader infile = null; String line; try { infile = new BufferedReader(new FileReader(openFileChooser.getSelectedFile())); } catch (FileNotFoundException e) { e.printStackTrace(); } try { while ((line = infile.readLine()) != null) { String[] lineParts = line.split("\t"); allWords.add( new Word( lineParts[0], Integer.parseInt(lineParts[1]), lineParts[2], Integer.parseInt(lineParts[3]))); } } catch (IOException e) { e.printStackTrace(); } } return allWords; }
private void copyWaveFile(String inFilename, String outFilename) { FileInputStream in = null; FileOutputStream out = null; long totalAudioLen = 0; long totalDataLen = totalAudioLen + 36; long longSampleRate = RECORDER_SAMPLERATE; int channels = 2; long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels / 8; byte[] data = new byte[bufferSize]; try { in = new FileInputStream(inFilename); out = new FileOutputStream(outFilename); totalAudioLen = in.getChannel().size(); totalDataLen = totalAudioLen + 36; // AppLog.logString("File size: " + totalDataLen); WriteWaveFileHeader(out, totalAudioLen, totalDataLen, longSampleRate, channels, byteRate); while (in.read(data) != -1) { out.write(data); } in.close(); out.close(); } catch (FileNotFoundException e) { Log.d("SAN", e.getMessage()); } catch (IOException e) { Log.d("SAN", e.getMessage()); } }
public static Map<String, ArrayList<String>> prepareMap() { Map<String, ArrayList<String>> symbolMap = new HashMap<String, ArrayList<String>>(); try { File file = new File("result.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String currentLine = scanner.nextLine(); // <AAPL,128.62> String temString = currentLine.substring(1, currentLine.length() - 1); String[] strArray = temString.split(","); String key = strArray[0]; String value = strArray[1]; ArrayList<String> priceList = new ArrayList<>(); if (symbolMap.containsKey(key)) { priceList = symbolMap.remove(key); } priceList.add(value); symbolMap.put(key, priceList); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } return symbolMap; }
public Bitmap getBitmapFromSd(String imgFilePath) { FileInputStream fis = null; try { fis = new FileInputStream(new File(imgFilePath)); // 文件输入流 Bitmap bmp = BitmapFactory.decodeStream(fis); return bmp; } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; }
@Test public void testAddPhrase() { int score = 50; AutoCompleteBuilderByTrie autoCompleteBuilder = new AutoCompleteBuilderByTrie(jedisHelper); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("./document/samplebook.trie.txt")); if (reader != null) { while (true) { String temp = reader.readLine(); if (temp == null) { break; } autoCompleteBuilder.addPhrase(temp, score); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
@Override public void onDownloaded(String result, int requestId) { // TODO Auto-generated method stub FileInputStream mFileInputStream = null; try { mFileInputStream = new FileInputStream(new File(result)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } ArrayList<Person> mList = null; switch (requestId) { case Constants.REQUEST_SAX_TYPE: mList = XmlTools.saxAnalysis(mFileInputStream, nodeName); break; case Constants.REQUEST_DOM_TYPE: mList = XmlTools.domAnalysis(mFileInputStream); break; case Constants.REQUEST_PULL_TYPE: mList = XmlTools.PullAnalysis(mFileInputStream, "UTF-8"); break; default: break; } MyAdapter myAdapter = new MyAdapter(this, mList); setListAdapter(myAdapter); if (mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } }
public static Map<String, Double> get(String fileNameProbModel) { java.io.BufferedReader br = null; try { br = new java.io.BufferedReader(new FileReader(fileNameProbModel)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String line; Map<String, Double> probModel = new HashMap<String, Double>(); try { while ((line = br.readLine()) != null) { String[] lines = line.split(","); probModel.put(lines[0], Double.parseDouble(lines[1])); } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return probModel; }