List of usage examples for org.apache.commons.io FileUtils contentEquals
public static boolean contentEquals(File file1, File file2) throws IOException
From source file:CSV.HandlingCSV.java
public void searchElements() { CSVReader reader;/*from w w w.jav a2s . c o m*/ List<String[]> entradas = new ArrayList<>(); try { try { if ((this.url == null) || (!this.verifyConnectUrl())) { File file = new File("download" + System.getProperty("file.separator") + doc_nome); if (!file.exists()) { File diretoria = new File("download"); diretoria.mkdir(); file.createNewFile(); } InputStream input = new FileInputStream(file); InputStreamReader r = new InputStreamReader(new FileInputStream(file)); reader = new CSVReader(new InputStreamReader(input, r.getEncoding()), ';'); if (reader.verifyReader()) { entradas = reader.readAll(); } } else { InputStream input; try { input = new URL(url).openStream(); reader = new CSVReader(new InputStreamReader(input), ';'); if (reader.verifyReader()) { entradas = reader.readAll(); File file = new File("download" + System.getProperty("file.separator") + doc_nome); if (!file.exists()) { File diretoria = new File("download"); diretoria.mkdir(); file.createNewFile(); novo = true; try (CSVWriter scv = new CSVWriter(new FileWriter(file), ';')) { scv.writeAll(entradas); scv.flush(); } } else { File file2 = new File("horario_disciplinas.csv"); try (CSVWriter scv = new CSVWriter(new FileWriter(file2), ';')) { scv.writeAll(entradas); scv.flush(); } if (FileUtils.contentEquals(file, file2)) { file2.delete(); } else { try (CSVWriter scv = new CSVWriter(new FileWriter(file), ';')) { file2.delete(); scv.writeAll(entradas); scv.flush(); novo = true; } } } } } catch (MalformedURLException ex) { Logger.getLogger(HandlingCSV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(HandlingCSV.class.getName()).log(Level.SEVERE, null, ex); } } } catch (UnsupportedEncodingException ex) { Logger.getLogger(HandlingCSV.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(HandlingCSV.class.getName()).log(Level.SEVERE, null, ex); } } catch (Exception ex) { } if (!entradas.isEmpty()) { ElementsCSV elemento; for (int i = 1; entradas.size() > i; i++) { if (entradas.get(i).length >= this.tamanho) { elemento = new ElementsCSV(Integer.valueOf(entradas.get(i)[valores[0]]), Integer.valueOf(entradas.get(i)[valores[1]]), Integer.valueOf(entradas.get(i)[valores[2]]), Integer.valueOf(entradas.get(i)[valores[3]]), Integer.valueOf(entradas.get(i)[valores[4]]), entradas.get(i)[valores[5]], entradas.get(i)[valores[6]], entradas.get(i)[valores[7]], entradas.get(i)[valores[8]], entradas.get(i)[valores[9]], entradas.get(i)[valores[10]]); elementos.add(elemento); } } } // tratamento para elementos contguos,no entanto, apurados como separados if (!elementos.isEmpty()) { for (int k = 0; k < elementos.size(); k++) { for (int j = 0; j < elementos.size(); j++) { if (elementos.get(k).getMaterialCode().equals(elementos.get(j).getMaterialCode())) { if (elementos.get(k).getCdSubject().equals(elementos.get(j).getCdSubject())) { if (elementos.get(k).getPersonCode().equals(elementos.get(k).getPersonCode())) { if (elementos.get(k).getDayWeek() == elementos.get(j).getDayWeek()) { if (elementos.get(k).getHourEnd() == elementos.get(j).getHourIni()) { if (elementos.get(k).getMinuteEnd() == elementos.get(j).getMinuteIni()) { elementos.get(k).setHourEnd(elementos.get(j).getHourEnd()); elementos.get(k).setMinuteEnd(elementos.get(j).getMinuteEnd()); elementos.remove(j); k = 0; } } } } } } } } } }
From source file:de.tudarmstadt.ukp.dkpro.core.io.text.TokenizedTextWriterTest.java
@Test public void testTokens() throws UIMAException, IOException { File targetFile = new File(context.getTestOutputFolder(), "TokenizedTextWriterTokensTest.out"); String text = "This is the 1st sentence .\nHere is another sentence ."; String typeName = Token.class.getTypeName(); File tokenized = new File("src/test/resources/tokenizedTexts/textTokenized.txt"); AnalysisEngineDescription writer = createEngineDescription(TokenizedTextWriter.class, TokenizedTextWriter.PARAM_TARGET_LOCATION, targetFile, TokenizedTextWriter.PARAM_FEATURE_PATH, typeName, TokenizedTextWriter.PARAM_SINGULAR_TARGET, true); TestRunner.runTest("id", writer, "en", text); assertTrue(FileUtils.contentEquals(tokenized, targetFile)); }
From source file:com.microsoft.alm.plugin.idea.common.setup.WindowsStartupTest.java
@Test public void testDoesKeyNeedUpdated_DiffFilesSameContents() throws Exception { TEST_EXE = File.createTempFile(TEST_CMD_NAME, ".cmd"); Mockito.when(FileUtils.contentEquals(TEST_EXE, mockCmdFile)).thenReturn(true); Mockito.when(mockCmdFile.getPath()).thenReturn(TEST_CMD_NAME); Mockito.when(Advapi32Util.registryGetStringValue(WinReg.HKEY_CLASSES_ROOT, WindowsStartup.VSOI_KEY, "")) .thenReturn(TEST_EXE.getPath() + " \"%1\""); Assert.assertFalse(WindowsStartup.doesKeyNeedUpdated(mockCmdFile)); }
From source file:com.starit.diamond.server.service.DiskService.java
public void saveToDisk(ConfigInfo configInfo) throws IOException { if (configInfo == null) throw new IllegalArgumentException("configInfo?"); if (!StringUtils.hasLength(configInfo.getDataId()) || StringUtils.containsWhitespace(configInfo.getDataId())) throw new IllegalArgumentException("dataId"); if (!StringUtils.hasLength(configInfo.getGroup()) || StringUtils.containsWhitespace(configInfo.getGroup())) throw new IllegalArgumentException("group"); if (!StringUtils.hasLength(configInfo.getContent())) throw new IllegalArgumentException("content"); final String basePath = WebUtils.getRealPath(servletContext, Constants.BASE_DIR); createDirIfNessary(basePath);/*from w w w . java 2 s .c o m*/ final String groupPath = WebUtils.getRealPath(servletContext, Constants.BASE_DIR + "/" + configInfo.getGroup()); createDirIfNessary(groupPath); String group = configInfo.getGroup(); String dataId = configInfo.getDataId(); dataId = SystemConfig.encodeDataIdForFNIfUnderWin(dataId); final String dataPath = WebUtils.getRealPath(servletContext, Constants.BASE_DIR + "/" + group + "/" + dataId); File targetFile = createFileIfNessary(dataPath); File tempFile = File.createTempFile(group + "-" + dataId, ".tmp"); FileOutputStream out = null; PrintWriter writer = null; try { out = new FileOutputStream(tempFile); BufferedOutputStream stream = new BufferedOutputStream(out); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, Constants.ENCODE))); configInfo.dump(writer); writer.flush(); } catch (Exception e) { log.error("??, tempFile:" + tempFile + ",targetFile:" + targetFile, e); } finally { if (writer != null) writer.close(); } String cacheKey = generateCacheKey(configInfo.getGroup(), configInfo.getDataId()); // if (this.modifyMarkCache.putIfAbsent(cacheKey, true) == null) { try { // ??? if (!FileUtils.contentEquals(tempFile, targetFile)) { try { // TODO ?, ??? , ?? FileUtils.copyFile(tempFile, targetFile); } catch (Throwable t) { log.error("??, tempFile:" + tempFile + ", targetFile:" + targetFile, t); SystemConfig.system_pause(); throw new RuntimeException(); } } tempFile.delete(); } finally { // this.modifyMarkCache.remove(cacheKey); } } else throw new ConfigServiceException("??"); }
From source file:com.microsoft.alm.plugin.idea.common.setup.ApplicationStartupTest.java
@Test public void testCacheIdeLocationOldEntry() throws Exception { File expectedFile = File.createTempFile("expectedLocation", ".csv"); writeToFile(expectedFile, IDEA_NAME + ",/current/location/of/ide\n"); writeToFile(new File(LOCATIONS_CSV_PATH), IDEA_NAME + ",/old/dir/for/ide\n"); ApplicationStartup appStartup = new ApplicationStartup(); appStartup.cacheIdeLocation(VSTS_DIR, "/current/location/of/ide"); Assert.assertTrue(FileUtils.contentEquals(expectedFile, new File(LOCATIONS_CSV_PATH))); }
From source file:edu.cornell.med.icb.goby.modes.TestReformatCompactReadsMode.java
/** * Validates that the reformat compact reads mode is capable of reformatting when * given positions that exactly match the length of the file. * * @throws IOException if there is a problem reading or writing to the files *//*from w w w . ja v a 2 s . c o m*/ @Test public void startAndEndAtExactLength() throws IOException { final ReformatCompactReadsMode reformat = new ReformatCompactReadsMode(); final String inputFilename = "test-data/compact-reads/s_1_sequence_short.compact-reads"; reformat.setInputFilenames(inputFilename); reformat.setStartPosition(0L); reformat.setEndPosition(new File(inputFilename).length() - 1); final String outputFilename = "test-results/reformat-test-start-end.compact-reads"; reformat.setOutputFile(outputFilename); reformat.execute(); assertTrue(FileUtils.contentEquals(new File(inputFilename), new File(outputFilename))); }
From source file:info.rsdev.xb4j.model.bindings.SimpleFileTypeTest.java
@Test public void testUnmarshallFileElement() throws Exception { byte[] buffer = "<Root><File>".concat(base64EncodedZipfile).concat("</File></Root>").getBytes(); ByteArrayInputStream stream = new ByteArrayInputStream(buffer); Object instance = this.model.toJava(XmlStreamFactory.makeReader(stream)); assertNotNull(instance);/*from w w w . j av a2 s .co m*/ assertSame(ObjectF.class, instance.getClass()); //Check the zipfile File file = ((ObjectF) instance).getFile(); assertNotNull(file); file.deleteOnExit(); //cleanup when tests are finished //do binary file-to-file comparison assertTrue(FileUtils.contentEquals(zipFile, file)); }
From source file:com.linkedin.pinot.segments.v1.creator.BitmapInvertedIndexCreatorTest.java
@Test public void testSingleValue() throws IOException { boolean singleValue = true; String colName = "single_value_col"; FieldSpec spec = new DimensionFieldSpec(colName, DataType.INT, singleValue); int numDocs = 20; int[] data = new int[numDocs]; int cardinality = 10; File indexDirHeap = new File("/tmp/indexDirHeap"); FileUtils.forceMkdir(indexDirHeap);// w w w . j a v a 2s . c o m indexDirHeap.mkdirs(); File indexDirOffHeap = new File("/tmp/indexDirOffHeap"); FileUtils.forceMkdir(indexDirOffHeap); indexDirOffHeap.mkdirs(); File bitmapIndexFileOffHeap = new File(indexDirOffHeap, colName + V1Constants.Indexes.BITMAP_INVERTED_INDEX_FILE_EXTENSION); File bitmapIndexFileHeap = new File(indexDirHeap, colName + V1Constants.Indexes.BITMAP_INVERTED_INDEX_FILE_EXTENSION); // GENERATE RANDOM DATA SET Random r = new Random(); Map<Integer, Set<Integer>> postingListMap = new HashMap<>(); for (int i = 0; i < cardinality; i++) { postingListMap.put(i, new LinkedHashSet<Integer>()); } for (int i = 0; i < numDocs; i++) { data[i] = r.nextInt(cardinality); LOGGER.debug("docId:" + i + " dictId:" + data[i]); postingListMap.get(data[i]).add(i); } for (int i = 0; i < cardinality; i++) { LOGGER.debug("Posting list for " + i + " : " + postingListMap.get(i)); } // GENERATE BITMAP USING OffHeapCreator and validate OffHeapBitmapInvertedIndexCreator offHeapCreator = new OffHeapBitmapInvertedIndexCreator(indexDirOffHeap, cardinality, numDocs, numDocs, spec); for (int i = 0; i < numDocs; i++) { offHeapCreator.add(i, data[i]); } offHeapCreator.seal(); validate(colName, bitmapIndexFileOffHeap, cardinality, postingListMap); // GENERATE BITMAP USING HeapCreator and validate HeapBitmapInvertedIndexCreator heapCreator = new HeapBitmapInvertedIndexCreator(indexDirHeap, cardinality, numDocs, 0, spec); for (int i = 0; i < numDocs; i++) { heapCreator.add(i, data[i]); } heapCreator.seal(); validate(colName, bitmapIndexFileHeap, cardinality, postingListMap); // assert that the file sizes and contents are the same Assert.assertEquals(bitmapIndexFileHeap.length(), bitmapIndexFileHeap.length()); Assert.assertTrue(FileUtils.contentEquals(bitmapIndexFileHeap, bitmapIndexFileHeap)); FileUtils.deleteQuietly(indexDirHeap); FileUtils.deleteQuietly(indexDirOffHeap); }
From source file:com.datatorrent.lib.io.fs.FixedBytesBlockReaderTest.java
@Test public void testBytesReceived() throws IOException { long blockSize = 1500; int noOfBlocks = (int) ((testMeta.dataFile.length() / blockSize) + (((testMeta.dataFile.length() % blockSize) == 0) ? 0 : 1)); testMeta.blockReader.beginWindow(1); for (int i = 0; i < noOfBlocks; i++) { FileSplitter.BlockMetadata blockMetadata = new FileSplitter.BlockMetadata(i * blockSize, i == noOfBlocks - 1 ? testMeta.dataFile.length() : (i + 1) * blockSize, testMeta.dataFile.getAbsolutePath(), i, i == noOfBlocks - 1); testMeta.blockReader.blocksMetadataInput.process(blockMetadata); }/*w w w . j a va 2 s .c om*/ testMeta.blockReader.endWindow(); List<Object> messages = testMeta.messageSink.collectedTuples; long totatBytesReceived = 0; File outputFile = new File(testMeta.output + "/reader_test_data.csv"); FileOutputStream outputStream = new FileOutputStream(outputFile); for (Object message : messages) { @SuppressWarnings("unchecked") AbstractBlockReader.ReaderRecord<Slice> msg = (AbstractBlockReader.ReaderRecord<Slice>) message; totatBytesReceived += msg.getRecord().length; outputStream.write(msg.getRecord().buffer); } outputStream.close(); Assert.assertEquals("number of bytes", testMeta.dataFile.length(), totatBytesReceived); FileUtils.contentEquals(testMeta.dataFile, outputFile); }
From source file:de.nbi.ontology.test.OntologyMatchTest.java
/** * Test, if terms are properly match to concept labels. The a list of terms * contains a term in each line.//from w w w .j a va 2 s . co m * * @param inFile * a list of terms * @throws IOException */ @SuppressWarnings("unchecked") @Test(dataProviderClass = TestFileProvider.class, dataProvider = "synonymTestFiles", groups = { "functest" }) public void synonyms(File inFile) throws IOException { log.info("Processing " + inFile.getName()); String basename = FilenameUtils.removeExtension(inFile.getAbsolutePath()); File outFile = new File(basename + ".out"); File resFile = new File(basename + ".res"); List<String> terms = FileUtils.readLines(inFile); PrintWriter w = new PrintWriter(new FileWriter(outFile)); for (String term : terms) { OntClass clazz = index.getModel().getOntClass(term); log.trace("** matching " + term); w.println(index.getSynonyms(clazz)); } w.flush(); w.close(); Assert.assertTrue(FileUtils.contentEquals(outFile, resFile)); }