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 ensureExists(File thing, String resource) { System.err.println("configfile = " + thing); if (!thing.exists()) { try { System.err.println("Creating: " + thing + " from " + resource); if (resource.indexOf("/") != 0) { resource = "/" + resource; } InputStream is = Config.class.getResourceAsStream(resource); if (is == null) { throw new NullPointerException("Can't find resource: " + resource); } getParentFile(thing).mkdirs(); OutputStream os = new FileOutputStream(thing); for (int next = is.read(); next != -1; next = is.read()) { os.write(next); } os.flush(); os.close(); } catch (FileNotFoundException fnfe) { throw new Error("Can't create resource: " + fnfe.getMessage()); } catch (IOException ioe) { throw new Error("Can't create resource: " + ioe.getMessage()); } } }
// Send File public void sendFile(String chunkName) throws IOException { OutputStream os = null; String currentDir = System.getProperty("user.dir"); chunkName = currentDir + "/src/srcFile/" + chunkName; File myFile = new File(chunkName); byte[] arrby = new byte[(int) myFile.length()]; try { FileInputStream fis = new FileInputStream(myFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(arrby, 0, arrby.length); os = csocket.getOutputStream(); System.out.println("Sending File."); os.write(arrby, 0, arrby.length); os.flush(); System.out.println("File Sent."); // os.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // os.close(); } }
public static Map<String, String> readProperties(InputStream inputStream) { Map<String, String> propertiesMap = null; try { propertiesMap = new LinkedHashMap<String, String>(); Properties properties = new Properties(); properties.load(inputStream); Enumeration<?> enumeration = properties.propertyNames(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); String value = (String) properties.get(key); propertiesMap.put(key, value); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return propertiesMap; }
/** * write categories to AIMLIF file * * @param cats array list of categories * @param filename AIMLIF filename */ public void writeIFCategories(ArrayList<Category> cats, String filename) { // System.out.println("writeIFCategories "+filename); BufferedWriter bw = null; File existsPath = new File(aimlif_path); if (existsPath.exists()) try { // Construct the bw object bw = new BufferedWriter(new FileWriter(aimlif_path + "/" + filename)); for (Category category : cats) { bw.write(Category.categoryToIF(category)); bw.newLine(); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { // Close the bw try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { ex.printStackTrace(); } } }
/* * Constructor (class entry point from java) * */ CDToolParser(String infilename, String outfile){ try{ //@ToDo make outfile stream, this prints to System.out instead out=System.out; unparsed_lines = new ArrayList<String>(); //spectral_entries = new ArrayList<SpectralEntry>(); spectral_table = new ArrayList<String>(); //File f = new File(infilename); FileInputStream fis= new FileInputStream(infilename); InputStreamReader isr = new InputStreamReader((InputStream)fis); BufferedReader br = new BufferedReader((Reader)isr); String line=""; while((line=br.readLine())!=null){ String p=ParseLine(line); } WriteExported(); }catch(FileNotFoundException fnfe){ fnfe.printStackTrace(); }catch(IOException ioe){ ioe.printStackTrace(); } }
/** * Read the topic-document relations * * @param fp * @return */ public static Map<Integer, Set<Integer>> readTopicDocuments(String fp) { Map<Integer, Set<Integer>> res = new HashMap<Integer, Set<Integer>>(); if (fp == null || fp.length() == 0) return res; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fp)))); String line = null; while ((line = reader.readLine()) != null) { String[] fields = line.split(" "); int docid = Integer.parseInt(fields[0]); int classid = Integer.parseInt(fields[1]); if (res.containsKey(classid)) { res.get(classid).add(docid); } else { Set<Integer> cset = new HashSet<Integer>(); cset.add(docid); res.put(classid, cset); } } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return Collections.unmodifiableMap(res); }
/** * Read the topic distribution from the file * * @param fp * @return */ public static Map<String, List<Double>> readTopicDist(String fp) { Map<String, List<Double>> res = new HashMap<String, List<Double>>(); if (fp == null || fp.length() == 0) return res; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fp)))); String line = null; while ((line = reader.readLine()) != null) { String[] fields = line.split(" "); int userid = Integer.parseInt(fields[0]); int queryid = Integer.parseInt(fields[1]); List<Double> probs = new ArrayList<Double>(); for (int i = 2; i < fields.length; i++) { probs.add(Double.parseDouble(fields[i].split(":")[1])); } res.put(userid + "-" + queryid, probs); } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return Collections.unmodifiableMap(res); }
public boolean load(File f) { if (f.exists() && f.isFile()) { list = new Vector(); try { FileInputStream fis = new FileInputStream(f); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); System.out.println("loading file:" + f); String tmp = br.readLine(); while (tmp != null) { // System.out.println("line" +tmp); list.add(new Data(tmp)); tmp = br.readLine(); } return true; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } System.err.println("bad file: " + f.getName()); return false; }
public void Cloner(String f1, String f2) { File file1 = new File(f1); File file2 = new File(f2); if (file2.exists()) { System.out.println( "That file already exists are you sure you want to continue, hit n to return and any other key to contine"); String str = System.console().readLine(); if (str == "n") { return; } } BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader(new FileReader(file1)); out = new PrintWriter(file2); String line; while ((line = in.readLine()) != null) { out.append(line + '\n'); } } catch (FileNotFoundException ex) { System.out.println("the file does not exist"); ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { System.out.println("okay thats been copied for you"); closeReader(in); out.close(); } }
public static void main(String[] args) throws IOException { String line = ""; ArrayList<String> list = new ArrayList<>(); try (Scanner scanner = new Scanner(System.in); BufferedReader reader = new BufferedReader(new FileReader(scanner.nextLine()))) { while ((line = reader.readLine()) != null) { list.addAll(Arrays.asList(line.split(" "))); } for (int i = 0; i < list.size(); i++) { String s = list.get(i); String reverse = new StringBuffer(s).reverse().toString(); if (list.indexOf(reverse) != -1 & !s.equals("") & !s.equals(reverse)) { result.add(new Pair(s, reverse)); list.remove(s); list.remove(reverse); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
static String getPropertyName(int propertyId, boolean bNamed) { if (bFirstTime) { bFirstTime = false; propertyNames = new Properties(); try { InputStream propertyStream = PSTFile.class.getResourceAsStream("/PropertyNames.txt"); if (propertyStream != null) { propertyNames.load(propertyStream); } else { propertyNames = null; } } catch (FileNotFoundException e) { propertyNames = null; e.printStackTrace(); } catch (IOException e) { propertyNames = null; e.printStackTrace(); } } if (propertyNames != null) { String key = String.format((bNamed ? "%08X" : "%04X"), propertyId); return propertyNames.getProperty(key); } return null; }
static { String bibFilePath = testDataParentPath + File.separator + "mhldMergeBibs1346.mrc"; try { RawRecordReader rawRecRdr = new RawRecordReader(new FileInputStream(new File(bibFilePath))); while (rawRecRdr.hasNext()) { RawRecord rawRec = rawRecRdr.next(); Record rec = rawRec.getAsRecord(true, false, "999", "MARC8"); String id = rec.getControlNumber(); // String id = RecordTestingUtils.getRecordIdFrom001(rec); ALL_UNMERGED_BIBS.put(id, rec); } } catch (FileNotFoundException e) { e.printStackTrace(); } bibFilePath = testDataParentPath + File.separator + "mhldMerged1346.mrc"; try { RawRecordReader rawRecRdr = new RawRecordReader(new FileInputStream(new File(bibFilePath))); while (rawRecRdr.hasNext()) { RawRecord rawRec = rawRecRdr.next(); Record rec = rawRec.getAsRecord(true, false, "999", "MARC8"); String id = rec.getControlNumber(); // String id = RecordTestingUtils.getRecordIdFrom001(rec); ALL_MERGED_BIB_RESULTS.put(id, rec); } } catch (FileNotFoundException e) { e.printStackTrace(); } }
private List<String> getTopicTweets(HttpServletRequest request) throws ServletException { final String topicFile = request.getParameter("topicFile"); final String fullFilePath = topicFile; List<String> listFiles = new ArrayList<String>(); Properties properties = new Properties(); try { properties.load(new FileInputStream(fullFilePath)); } catch (FileNotFoundException e) { LOGGER.error("missing file for in topic tweets: '" + fullFilePath + "'" + e.getMessage()); e.printStackTrace(); } catch (IOException e) { LOGGER.error("can't read file for in topic tweets: '" + fullFilePath + "'" + e.getMessage()); e.printStackTrace(); } for (Entry<Object, Object> propertyEntry : properties.entrySet()) { String key = (String) propertyEntry.getKey(); if (key.startsWith("inTopic")) { listFiles.add((String) propertyEntry.getValue()); } } List<String> tweets = new ArrayList<String>(); for (String filtFile : listFiles) { tweets.addAll(parseTweetsFromFile(filtFile)); } return tweets; }
private List<String> getOutOfTopicTweets(HttpServletRequest request) throws ServletException { String topicFile = request.getParameter("topicFile"); List<String> listFiles = new ArrayList<String>(); Properties properties = new Properties(); try { properties.load(new FileInputStream(topicFile)); } catch (FileNotFoundException e) { final String emsg = "missing file for out of topic tweets: '" + topicFile + "'" + e.getMessage(); LOGGER.error(emsg); throw new ServletException(emsg, e); } catch (IOException e) { final String emsg = "can't read file for out of topic tweets: '" + topicFile + "'" + e.getMessage(); LOGGER.error(emsg); throw new ServletException(emsg); } for (Entry<Object, Object> propertyEntry : properties.entrySet()) { String key = (String) propertyEntry.getKey(); if (key.startsWith("outOfTopic")) { listFiles.add((String) propertyEntry.getValue()); } } List<String> tweets = new ArrayList<String>(); for (String filtFile : listFiles) { tweets.addAll(parseTweetsFromFile(filtFile)); } return tweets; }
private void init(String testClass, String testName, TestState state) { if (writeToFile) { File fileToWrite = createFile(testClass, testName); if (fileToWrite == null) { System.err.println( "Cannot create file for " + testClass + "." + testName + ". Writing to STDOUT"); state.printStream = System.out; } else { try { state.printStream = new PrintStream(new FileOutputStream(fileToWrite)); System.out.println( testClass + "." + testName + " writing to " + fileToWrite.getAbsolutePath()); } catch (FileNotFoundException e) { e.printStackTrace(); state.printStream = System.out; } } } else { state.printStream = System.out; } // sanity check if (state.printStream == null) { throw new IllegalStateException("PrintStream cannot be null!!"); } }
public static void main(String[] args) throws IOException { PGF gr = null; try { gr = PGF.readPGF( "/home/krasimir/www.grammaticalframework.org/examples/phrasebook/Phrasebook.pgf"); } catch (FileNotFoundException e) { e.printStackTrace(); return; } catch (PGFError e) { e.printStackTrace(); return; } Type typ = gr.getFunctionType("Bulgarian"); System.out.println(typ.getCategory()); System.out.println(gr.getAbstractName()); for (Map.Entry<String, Concr> entry : gr.getLanguages().entrySet()) { System.out.println( entry.getKey() + " " + entry.getValue() + " " + entry.getValue().getName()); } Concr eng = gr.getLanguages().get("SimpleEng"); try { for (ExprProb ep : eng.parse(gr.getStartCat(), "persons who work with Malmö")) { System.out.println("[" + ep.getProb() + "] " + ep.getExpr()); } } catch (ParseError e) { System.out.println("Parsing failed at token \"" + e.getToken() + "\""); } }
/** * read the transition matrix from the file * * @param fp * @return */ public static Map<Integer, Set<Integer>> readTransitionMatrix(String fp) { Map<Integer, Set<Integer>> res = new HashMap<Integer, Set<Integer>>(); if (fp == null || fp.length() == 0) return res; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fp)))); String line = null; while ((line = reader.readLine()) != null) { String[] fields = line.split(" "); int from = Integer.parseInt(fields[0]); int to = Integer.parseInt(fields[1]); if (res.containsKey(from)) { res.get(from).add(to); } else { Set<Integer> cset = new HashSet<Integer>(); cset.add(to); res.put(from, cset); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return Collections.unmodifiableMap(res); }
/** * Creates a DBFWriter which can append to records to an existing DBF file. * * @param dbfFile. The file passed in shouls be a valid DBF file. * @exception Throws DBFException if the passed in file does exist but not a valid DBF file, or if * an IO error occurs. */ public DBFWriter(File dbfFile) throws DBFException { try { this.raf = new RandomAccessFile(dbfFile, "rw"); /* before proceeding check whether the passed in File object is an empty/non-existent file or not. */ if (!dbfFile.exists() || dbfFile.length() == 0) { this.header = new DBFHeader(); return; } header = new DBFHeader(); this.header.read(raf); /* position file pointer at the end of the raf */ this.raf.seek(this.raf.length() - 1 /* to ignore the END_OF_DATA byte at EoF */); } catch (FileNotFoundException e) { throw new DBFException("Specified file is not found. " + e.getMessage()); } catch (IOException e) { throw new DBFException(e.getMessage() + " while reading header"); } this.recordCount = this.header.numberOfRecords; }
/** * @param fname String filename to read matrix from * @return Map of lists, 1 indexed representing the adjacency matrix */ public Map<Integer, List<Integer>> readAdjacencyMatrix(String fname) { Map<Integer, List<Integer>> adjMatrix = new HashMap<>(); int i = 1; try { BufferedReader br = new BufferedReader(new FileReader(fname)); String line; while ((line = br.readLine()) != null) { List<String> words = Arrays.asList(line.split("\\s*")); List<Integer> wordVals = new ArrayList<>(); for (String w : words) { if (w.equals("1") || w.equals("0")) { wordVals.add(Integer.parseInt(w)); } } adjMatrix.put(i, wordVals); i += 1; } br.close(); return adjMatrix; } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } }
public static Set<RepairedCell> readTruth(String fileRoute) { File file = new File(fileRoute); Set<RepairedCell> truth = new HashSet<RepairedCell>(); if (!file.exists()) { System.out.println(fileRoute + "文件不存在,无法测试!"); return truth; } try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line = null; while (null != (line = br.readLine())) { String[] paras = line.split(","); RepairedCell cell = null; if (paras.length == 2) { cell = new RepairedCell(Integer.parseInt(paras[0]), paras[1], ""); } else { cell = new RepairedCell(Integer.parseInt(paras[0]), paras[1], paras[2]); } truth.add(cell); } br.close(); fr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return truth; }
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); } }
private String ReadWholeFileToString(String filename) { File file = new File(filename); StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String text = null; // repeat until all lines is read while ((text = reader.readLine()) != null) { contents.append(text).append(System.getProperty("line.separator")); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } // show file contents here return contents.toString(); }
FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } }
private static ArrayList<Integer> getChromosomalBoundaries(String fileName, int chrColumnNumber) { ArrayList<Integer> boundaries = new ArrayList<Integer>(); String line = ""; try { BufferedReader br = new BufferedReader(new FileReader(fileName)); int prevChr = 0; int lineNumber = 1; while ((line = br.readLine()) != null) { int chr; try { chr = Integer.parseInt((line.split("\t")[chrColumnNumber].substring(3))); } catch (NumberFormatException e) { chr = 0; // for now, ignore X, Y, M chromosomes } if (chr != prevChr) boundaries.add(lineNumber - 1); lineNumber++; prevChr = chr; } boundaries.add(lineNumber); } catch (FileNotFoundException e) { System.err.println("File Not Found: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IO Exception: " + e.getMessage()); e.printStackTrace(); } return boundaries; }
private Core() { boolean f = false; try { for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = (NetworkInterface) en.nextElement(); for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { String ipAddress = inetAddress.getHostAddress().toString(); this.ip = inetAddress; f = true; break; } } if (f) break; } } catch (SocketException ex) { ex.printStackTrace(); System.exit(1); } this.teams = new HashMap<String, Team>(); this.judges = new HashMap<String, Judge>(); this.problems = new HashMap<String, ProblemInfo>(); this.scheduler = new Scheduler(); this.timer = new ContestTimer(300 * 60); try { readConfigure(); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(1); } this.scoreBoardHttpServer = new ScoreBoardHttpServer(this.scoreBoardPort); }
private static List<String> readQueryFile(String query_file_path) throws IOException { // TODO Auto-generated method stub String str; // StringBuffer query = new StringBuffer(); List<String> query_list = new ArrayList<String>(); try { File query_file = new File(query_file_path); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(query_file))); while ((str = br.readLine()) != null) { // query.append(str.trim()); int startIndex = 0; String q = str.trim(); // q = str.replaceAll("[,!?\\()\"]", ""); if (q.length() > 0) { int endIndexofStop = q.lastIndexOf("."); query_list.add(q.substring(startIndex, endIndexofStop).trim()); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return query_list; }
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(); } }
public static void main(String[] args) { String testDataLocation = "testData/HighResolutionTerrain/"; HashMap<String, Sector> sectors = new HashMap<String, Sector>(); sectors.put( testDataLocation + "HRTOutputTest01.txt", Sector.fromDegrees(37.8, 38.3, -120, -119.3)); sectors.put( testDataLocation + "HRTOutputTest02.txt", Sector.fromDegrees(32.34767, 32.77991, 70.88239, 71.47658)); sectors.put( testDataLocation + "HRTOutputTest03.txt", Sector.fromDegrees(32.37825, 71.21130, 32.50050, 71.37926)); try { if (args.length > 0 && args[0].equals("-generateTestData")) { for (Map.Entry<String, Sector> sector : sectors.entrySet()) { String filePath = sector.getKey(); generateReferenceValues(filePath, sector.getValue()); } } for (Map.Entry<String, Sector> sector : sectors.entrySet()) { String filePath = sector.getKey(); ArrayList<Position> referencePositions = readReferencePositions(filePath); ArrayList<Position> computedPositions = computeElevations(referencePositions); testPositions(filePath, referencePositions, computedPositions); } } catch (FileNotFoundException e) { e.printStackTrace(); } }
public Inference() { PrintStream out = null; try { out = new PrintStream(new FileOutputStream("output_1.txt")); } catch (FileNotFoundException e1) { e1.printStackTrace(); } System.setOut(out); }