List of usage examples for java.io FileOutputStream close
public void close() throws IOException
From source file:MainClass.java
public static void main(String[] args) { File aFile = new File("afile.txt"); FileOutputStream outputFile = null; try {/* w ww. j a v a 2 s .c o m*/ outputFile = new FileOutputStream(aFile, true); System.out.println("File stream created successfully."); } catch (FileNotFoundException e) { e.printStackTrace(System.err); } ByteBuffer buf = ByteBuffer.allocate(1024); System.out.println("\nByte buffer:"); System.out.printf("position = %2d Limit = %4d capacity = %4d%n", buf.position(), buf.limit(), buf.capacity()); // Create a view buffer CharBuffer charBuf = buf.asCharBuffer(); System.out.println("Char view buffer:"); System.out.printf("position = %2d Limit = %4d capacity = %4d%n", charBuf.position(), charBuf.limit(), charBuf.capacity()); try { outputFile.close(); // Close the O/P stream & the channel } catch (IOException e) { e.printStackTrace(System.err); } }
From source file:Main.java
public static void main(String[] args) throws Exception { String phrase = new String("www.java2s.com\n"); File aFile = new File("test.txt"); FileOutputStream outputFile = null; outputFile = new FileOutputStream(aFile, true); System.out.println("File stream created successfully."); FileChannel outChannel = outputFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(1024); System.out.println("New buffer: position = " + buf.position() + "\tLimit = " + buf.limit() + "\tcapacity = " + buf.capacity()); // Load the data into the buffer for (char ch : phrase.toCharArray()) { buf.putChar(ch);//from w w w .jav a 2 s .c o m } System.out.println("Buffer after loading: position = " + buf.position() + "\tLimit = " + buf.limit() + "\tcapacity = " + buf.capacity()); buf.flip(); System.out.println("Buffer after flip: position = " + buf.position() + "\tLimit = " + buf.limit() + "\tcapacity = " + buf.capacity()); outChannel.write(buf); outputFile.close(); System.out.println("Buffer contents written to file."); }
From source file:listfiles.ListFiles.java
/** * @param args the command line arguments *///from w ww . ja v a 2s.c om public static void main(String[] args) { // TODO code application logic here BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String folderPath = ""; String fileName = "DirectoryFiles.xlsx"; try { System.out.println("Folder path :"); folderPath = reader.readLine(); //System.out.println("Output File Name :"); //fileName = reader.readLine(); XSSFWorkbook wb = new XSSFWorkbook(); FileOutputStream fileOut = new FileOutputStream(folderPath + "\\" + fileName); XSSFSheet sheet1 = wb.createSheet("Files"); int row = 0; Stream<Path> stream = Files.walk(Paths.get(folderPath)); Iterator<Path> pathIt = stream.iterator(); String ext = ""; while (pathIt.hasNext()) { Path filePath = pathIt.next(); Cell cell1 = checkRowCellExists(sheet1, row, 0); Cell cell2 = checkRowCellExists(sheet1, row, 1); row++; ext = FilenameUtils.getExtension(filePath.getFileName().toString()); cell1.setCellValue(filePath.getFileName().toString()); cell2.setCellValue(ext); } sheet1.autoSizeColumn(0); sheet1.autoSizeColumn(1); wb.write(fileOut); fileOut.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Program Finished"); }
From source file:MainClass.java
public static void main(String[] args) { long[] primes = new long[] { 1, 2, 3, 5, 7 }; File aFile = new File("C:/test/primes.bin"); FileOutputStream outputFile = null; try {//from ww w .jav a2 s . c om outputFile = new FileOutputStream(aFile); } catch (FileNotFoundException e) { e.printStackTrace(System.err); } FileChannel file = outputFile.getChannel(); final int BUFFERSIZE = 100; ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE); LongBuffer longBuf = buf.asLongBuffer(); int primesWritten = 0; while (primesWritten < primes.length) { longBuf.put(primes, primesWritten, min(longBuf.capacity(), primes.length - primesWritten)); buf.limit(8 * longBuf.position()); try { file.write(buf); primesWritten += longBuf.position(); } catch (IOException e) { e.printStackTrace(System.err); } longBuf.clear(); buf.clear(); } try { System.out.println("File written is " + file.size() + "bytes."); outputFile.close(); } catch (IOException e) { e.printStackTrace(System.err); } }
From source file:com.era7.bioinfo.annotation.AutomaticQualityControl.java
public static void main(String[] args) { if (args.length != 4) { System.out.println("This program expects four parameters: \n" + "1. Gene annotation XML filename \n" + "2. Reference protein set (.fasta)\n" + "3. Output TXT filename\n" + "4. Initial Blast XML results filename (the one used at the very beginning of the semiautomatic annotation process)\n"); } else {/*from w w w. j a v a 2s . com*/ BufferedWriter outBuff = null; try { File inFile = new File(args[0]); File fastaFile = new File(args[1]); File outFile = new File(args[2]); File blastFile = new File(args[3]); //Primero cargo todos los datos del archivo xml del blast BufferedReader buffReader = new BufferedReader(new FileReader(blastFile)); StringBuilder stBuilder = new StringBuilder(); String line = null; while ((line = buffReader.readLine()) != null) { stBuilder.append(line); } buffReader.close(); System.out.println("Creating blastoutput..."); BlastOutput blastOutput = new BlastOutput(stBuilder.toString()); System.out.println("BlastOutput created! :)"); stBuilder.delete(0, stBuilder.length()); HashMap<String, String> blastProteinsMap = new HashMap<String, String>(); ArrayList<Iteration> iterations = blastOutput.getBlastOutputIterations(); for (Iteration iteration : iterations) { blastProteinsMap.put(iteration.getQueryDef().split("\\|")[1].trim(), iteration.toString()); } //freeing some memory blastOutput = null; //------------------------------------------------------------------------ //Initializing writer for output file outBuff = new BufferedWriter(new FileWriter(outFile)); //reading gene annotation xml file..... buffReader = new BufferedReader(new FileReader(inFile)); stBuilder = new StringBuilder(); line = null; while ((line = buffReader.readLine()) != null) { stBuilder.append(line); } buffReader.close(); XMLElement genesXML = new XMLElement(stBuilder.toString()); //freeing some memory I don't need anymore stBuilder.delete(0, stBuilder.length()); //reading file with the reference proteins set ArrayList<String> proteinsReferenceSet = new ArrayList<String>(); buffReader = new BufferedReader(new FileReader(fastaFile)); while ((line = buffReader.readLine()) != null) { if (line.charAt(0) == '>') { proteinsReferenceSet.add(line.split("\\|")[1]); } } buffReader.close(); Element pGenes = genesXML.asJDomElement().getChild(PredictedGenes.TAG_NAME); List<Element> contigs = pGenes.getChildren(ContigXML.TAG_NAME); System.out.println("There are " + contigs.size() + " contigs to be checked... "); outBuff.write("There are " + contigs.size() + " contigs to be checked... \n"); outBuff.write("Proteins reference set: \n"); for (String st : proteinsReferenceSet) { outBuff.write(st + ","); } outBuff.write("\n"); for (Element elem : contigs) { ContigXML contig = new ContigXML(elem); //escribo el id del contig en el que estoy outBuff.write("Checking contig: " + contig.getId() + "\n"); outBuff.flush(); List<XMLElement> geneList = contig.getChildrenWith(PredictedGene.TAG_NAME); System.out.println("geneList.size() = " + geneList.size()); int numeroDeGenesParaAnalizar = geneList.size() / FACTOR; if (numeroDeGenesParaAnalizar == 0) { numeroDeGenesParaAnalizar++; } ArrayList<Integer> indicesUtilizados = new ArrayList<Integer>(); outBuff.write("\nThe contig has " + geneList.size() + " predicted genes, let's analyze: " + numeroDeGenesParaAnalizar + "\n"); for (int j = 0; j < numeroDeGenesParaAnalizar; j++) { int geneIndex; boolean geneIsDismissed = false; do { geneIsDismissed = false; geneIndex = (int) Math.round(Math.floor(Math.random() * geneList.size())); PredictedGene tempGene = new PredictedGene(geneList.get(geneIndex).asJDomElement()); if (tempGene.getStatus().equals(PredictedGene.STATUS_DISMISSED)) { geneIsDismissed = true; } } while (indicesUtilizados.contains(new Integer(geneIndex)) && geneIsDismissed); indicesUtilizados.add(geneIndex); System.out.println("geneIndex = " + geneIndex); //Ahora hay que sacar el gen correspondiente al indice y hacer el control de calidad PredictedGene gene = new PredictedGene(geneList.get(geneIndex).asJDomElement()); outBuff.write("\nAnalyzing gene with id: " + gene.getId() + " , annotation uniprot id: " + gene.getAnnotationUniprotId() + "\n"); outBuff.write("eValue: " + gene.getEvalue() + "\n"); //--------------PETICION POST HTTP BLAST---------------------- PostMethod post = new PostMethod(BLAST_URL); post.addParameter("program", "blastx"); post.addParameter("sequence", gene.getSequence()); post.addParameter("database", "uniprotkb"); post.addParameter("email", "ppareja@era7.com"); post.addParameter("exp", "1e-10"); post.addParameter("stype", "dna"); // execute the POST HttpClient client = new HttpClient(); int status = client.executeMethod(post); System.out.println("status post = " + status); InputStream inStream = post.getResponseBodyAsStream(); String fileName = "jobid.txt"; FileOutputStream outStream = new FileOutputStream(new File(fileName)); byte[] buffer = new byte[1024]; int len; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //Once the file is created I just have to read one line in order to extract the job id buffReader = new BufferedReader(new FileReader(new File(fileName))); String jobId = buffReader.readLine(); buffReader.close(); System.out.println("jobId = " + jobId); //--------------HTTP CHECK JOB STATUS REQUEST---------------------- GetMethod get = new GetMethod(CHECK_JOB_STATUS_URL + jobId); String jobStatus = ""; do { try { Thread.sleep(1000);//sleep for 1000 ms } catch (InterruptedException ie) { //If this thread was intrrupted by nother thread } status = client.executeMethod(get); //System.out.println("status get = " + status); inStream = get.getResponseBodyAsStream(); fileName = "jobStatus.txt"; outStream = new FileOutputStream(new File(fileName)); while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //Once the file is created I just have to read one line in order to extract the job id buffReader = new BufferedReader(new FileReader(new File(fileName))); jobStatus = buffReader.readLine(); //System.out.println("jobStatus = " + jobStatus); buffReader.close(); } while (!jobStatus.equals(FINISHED_JOB_STATUS)); //Once I'm here the blast should've already finished //--------------JOB RESULTS HTTP REQUEST---------------------- get = new GetMethod(JOB_RESULT_URL + jobId + "/out"); status = client.executeMethod(get); System.out.println("status get = " + status); inStream = get.getResponseBodyAsStream(); fileName = "jobResults.txt"; outStream = new FileOutputStream(new File(fileName)); while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); //--------parsing the blast results file----- TreeSet<GeneEValuePair> featuresBlast = new TreeSet<GeneEValuePair>(); buffReader = new BufferedReader(new FileReader(new File(fileName))); while ((line = buffReader.readLine()) != null) { if (line.length() > 3) { String prefix = line.substring(0, 3); if (prefix.equals("TR:") || prefix.equals("SP:")) { String[] columns = line.split(" "); String id = columns[1]; //System.out.println("id = " + id); String e = ""; String[] arraySt = line.split("\\.\\.\\."); if (arraySt.length > 1) { arraySt = arraySt[1].trim().split(" "); int contador = 0; for (int k = 0; k < arraySt.length && contador <= 2; k++) { String string = arraySt[k]; if (!string.equals("")) { contador++; if (contador == 2) { e = string; } } } } else { //Number before e- String[] arr = arraySt[0].split("e-")[0].split(" "); String numeroAntesE = arr[arr.length - 1]; String numeroDespuesE = arraySt[0].split("e-")[1].split(" ")[0]; e = numeroAntesE + "e-" + numeroDespuesE; } double eValue = Double.parseDouble(e); //System.out.println("eValue = " + eValue); GeneEValuePair g = new GeneEValuePair(id, eValue); featuresBlast.add(g); } } } GeneEValuePair currentGeneEValuePair = new GeneEValuePair(gene.getAnnotationUniprotId(), gene.getEvalue()); System.out.println("currentGeneEValuePair.id = " + currentGeneEValuePair.id); System.out.println("currentGeneEValuePair.eValue = " + currentGeneEValuePair.eValue); boolean blastContainsGene = false; for (GeneEValuePair geneEValuePair : featuresBlast) { if (geneEValuePair.id.equals(currentGeneEValuePair.id)) { blastContainsGene = true; //le pongo la e que tiene en el wu-blast para poder comparar currentGeneEValuePair.eValue = geneEValuePair.eValue; break; } } if (blastContainsGene) { outBuff.write("The protein was found in the WU-BLAST result.. \n"); //Una vez que se que esta en el blast tengo que ver que sea la mejor GeneEValuePair first = featuresBlast.first(); outBuff.write("Protein with best eValue according to the WU-BLAST result: " + first.id + " , " + first.eValue + "\n"); if (first.id.equals(currentGeneEValuePair.id)) { outBuff.write("Proteins with best eValue match up \n"); } else { if (first.eValue == currentGeneEValuePair.eValue) { outBuff.write( "The one with best eValue is not the same protein but has the same eValue \n"); } else if (first.eValue > currentGeneEValuePair.eValue) { outBuff.write( "The one with best eValue is not the same protein but has a worse eValue :) \n"); } else { outBuff.write( "The best protein from BLAST has an eValue smaller than ours, checking if it's part of the reference set...\n"); //System.exit(-1); if (proteinsReferenceSet.contains(first.id)) { //The protein is in the reference set and that shouldn't happen outBuff.write( "The protein was found on the reference set, checking if it belongs to the same contig...\n"); String iterationSt = blastProteinsMap.get(gene.getAnnotationUniprotId()); if (iterationSt != null) { outBuff.write( "The protein was found in the BLAST used at the beginning of the annotation process.\n"); Iteration iteration = new Iteration(iterationSt); ArrayList<Hit> hits = iteration.getIterationHits(); boolean contigFound = false; Hit errorHit = null; for (Hit hit : hits) { if (hit.getHitDef().indexOf(contig.getId()) >= 0) { contigFound = true; errorHit = hit; break; } } if (contigFound) { outBuff.write( "ERROR: A hit from the same contig was find in the Blast file: \n" + errorHit.toString() + "\n"); } else { outBuff.write("There is no hit with the same contig! :)\n"); } } else { outBuff.write( "The protein is NOT in the BLAST used at the beginning of the annotation process.\n"); } } else { //The protein was not found on the reference set so everything's ok outBuff.write( "The protein was not found on the reference, everything's ok :)\n"); } } } } else { outBuff.write("The protein was NOT found on the WU-BLAST !! :( \n"); //System.exit(-1); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { try { //closing outputfile outBuff.close(); } catch (IOException ex) { Logger.getLogger(AutomaticQualityControl.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:MainClass.java
public static void main(String[] args) { String phrase = new String("text \n"); String dirname = "C:/test"; String filename = "charData.txt"; File dir = new File(dirname); File aFile = new File(dir, filename); FileOutputStream outputFile = null; try {/*from w w w . j a v a 2 s. co m*/ outputFile = new FileOutputStream(aFile, true); System.out.println("File stream created successfully."); } catch (FileNotFoundException e) { e.printStackTrace(System.err); } FileChannel outChannel = outputFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(1024); System.out.println("New buffer: position = " + buf.position() + "\tLimit = " + buf.limit() + "\tcapacity = " + buf.capacity()); for (char ch : phrase.toCharArray()) { buf.putChar(ch); } System.out.println("Buffer after loading: position = " + buf.position() + "\tLimit = " + buf.limit() + "\tcapacity = " + buf.capacity()); buf.flip(); System.out.println("Buffer after flip: position = " + buf.position() + "\tLimit = " + buf.limit() + "\tcapacity = " + buf.capacity()); try { outChannel.write(buf); outputFile.close(); System.out.println("Buffer contents written to file."); } catch (IOException e) { e.printStackTrace(System.err); } }
From source file:com.servoy.extensions.plugins.http.HttpProvider.java
public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println("Use: ContentFetcher mainurl contenturl destdir"); //$NON-NLS-1$ System.out.println(/*from ww w .j a va 2 s.c o m*/ "Example: ContentFetcher http://site.com http://site.com/dir[0-2]/image_A[001-040].jpg c:/temp"); //$NON-NLS-1$ System.out.println( "Result: accessing http://site.com for cookie, reading http://site.com/dir1/image_A004.jpg writing c:/temp/dir_1_image_A004.jpg"); //$NON-NLS-1$ } else { String url = args[1]; String destdir = args[2]; List parts = new ArrayList(); int dir_from = 0; int dir_to = 0; int dir_fill = 0; int from = 0; int to = 0; int fill = 0; StringTokenizer tk = new StringTokenizer(url, "[]", true); //$NON-NLS-1$ boolean hasDir = (tk.countTokens() > 5); boolean inDir = hasDir; System.out.println("hasDir " + hasDir); //$NON-NLS-1$ boolean inTag = false; while (tk.hasMoreTokens()) { String token = tk.nextToken(); if (token.equals("[")) //$NON-NLS-1$ { inTag = true; continue; } if (token.equals("]")) //$NON-NLS-1$ { inTag = false; if (inDir) inDir = false; continue; } if (inTag) { int idx = token.indexOf('-'); String s_from = token.substring(0, idx); int a_from = new Integer(s_from).intValue(); int a_fill = s_from.length(); int a_to = new Integer(token.substring(idx + 1)).intValue(); if (inDir) { dir_from = a_from; dir_to = a_to; dir_fill = a_fill; } else { from = a_from; to = a_to; fill = a_fill; } } else { parts.add(token); } } DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); HttpGet main = new HttpGet(args[0]); HttpResponse res = client.execute(main); ; int main_rs = res.getStatusLine().getStatusCode(); if (main_rs != 200) { System.out.println("main page retrieval failed " + main_rs); //$NON-NLS-1$ return; } for (int d = dir_from; d <= dir_to; d++) { String dir_number = "" + d; //$NON-NLS-1$ if (dir_fill > 1) { dir_number = "000000" + d; //$NON-NLS-1$ int dir_digits = (int) (Math.log(fill) / Math.log(10)); System.out.println("dir_digits " + dir_digits); //$NON-NLS-1$ dir_number = dir_number.substring(dir_number.length() - (dir_fill - dir_digits), dir_number.length()); } for (int i = from; i <= to; i++) { try { String number = "" + i; //$NON-NLS-1$ if (fill > 1) { number = "000000" + i; //$NON-NLS-1$ int digits = (int) (Math.log(fill) / Math.log(10)); System.out.println("digits " + digits); //$NON-NLS-1$ number = number.substring(number.length() - (fill - digits), number.length()); } int part = 0; StringBuffer surl = new StringBuffer((String) parts.get(part++)); if (hasDir) { surl.append(dir_number); surl.append(parts.get(part++)); } surl.append(number); surl.append(parts.get(part++)); System.out.println("reading url " + surl); //$NON-NLS-1$ int indx = surl.toString().lastIndexOf('/'); StringBuffer sfile = new StringBuffer(destdir); sfile.append("\\"); //$NON-NLS-1$ if (hasDir) { sfile.append("dir_"); //$NON-NLS-1$ sfile.append(dir_number); sfile.append("_"); //$NON-NLS-1$ } sfile.append(surl.toString().substring(indx + 1)); File file = new File(sfile.toString()); if (file.exists()) { file = new File("" + System.currentTimeMillis() + sfile.toString()); } System.out.println("write file " + file.getAbsolutePath()); //$NON-NLS-1$ // URL iurl = createURLFromString(surl.toString()); HttpGet get = new HttpGet(surl.toString()); HttpResponse response = client.execute(get); int result = response.getStatusLine().getStatusCode(); System.out.println("page http result " + result); //$NON-NLS-1$ if (result == 200) { InputStream is = response.getEntity().getContent(); FileOutputStream fos = new FileOutputStream(file); Utils.streamCopy(is, fos); fos.close(); } } catch (Exception e) { System.err.println(e); } } } } }
From source file:FTPConnect.FTPBajarArchivo.java
public static void main(String[] args) throws IOException { FTPClient ftpClient = new FTPClient(); FileOutputStream fos = null; boolean result; try {/*from w w w .j av a 2 s . co m*/ // Connect to the localhost ftpClient.connect("localhost"); // login to ftp server result = ftpClient.login("", ""); if (result == true) { System.out.println("Successfully logged in!"); } else { System.out.println("Login Fail!"); return; } String fileName = "uploadfile.txt"; fos = new FileOutputStream(fileName); // Download file from the ftp server result = ftpClient.retrieveFile(fileName, fos); if (result == true) { System.out.println("File downloaded successfully !"); } else { System.out.println("File downloading failed !"); } ftpClient.logout(); } catch (FTPConnectionClosedException e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } ftpClient.disconnect(); } catch (FTPConnectionClosedException e) { System.err.println(e); } } }
From source file:MainClass.java
public static void main(String[] args) { int count = 100; long[] numbers = new long[count]; for (int i = 0; i < numbers.length; i++) { numbers[i] = i;//w w w . j av a 2 s .c o m } File aFile = new File("data.bin"); FileOutputStream outputFile = null; try { outputFile = new FileOutputStream(aFile); } catch (FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); } FileChannel file = outputFile.getChannel(); final int BUFFERSIZE = 100; ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE); LongBuffer longBuf = buf.asLongBuffer(); int numberWritten = 0; while (numberWritten < numbers.length) { longBuf.put(numbers, numberWritten, min(longBuf.capacity(), numbers.length - numberWritten)); buf.limit(8 * longBuf.position()); try { file.write(buf); numberWritten += longBuf.position(); } catch (IOException e) { e.printStackTrace(System.err); System.exit(1); } longBuf.clear(); buf.clear(); } try { System.out.println("File written is " + file.size() + " bytes."); outputFile.close(); } catch (IOException e) { e.printStackTrace(System.err); System.exit(1); } }
From source file:MainClass.java
public static void main(String[] args) { String phrase = new String("www.java2s.com\n"); File aFile = new File("test.txt"); FileOutputStream outputFile = null; try {//from www . j a v a2 s.c om outputFile = new FileOutputStream(aFile, true); System.out.println("File stream created successfully."); } catch (FileNotFoundException e) { e.printStackTrace(System.err); } FileChannel outChannel = outputFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(1024); System.out.println("New buffer: position = " + buf.position() + "\tLimit = " + buf.limit() + "\tcapacity = " + buf.capacity()); // Load the data into the buffer for (char ch : phrase.toCharArray()) { buf.putChar(ch); } System.out.println("Buffer after loading: position = " + buf.position() + "\tLimit = " + buf.limit() + "\tcapacity = " + buf.capacity()); buf.flip(); System.out.println("Buffer after flip: position = " + buf.position() + "\tLimit = " + buf.limit() + "\tcapacity = " + buf.capacity()); try { outChannel.write(buf); outputFile.close(); System.out.println("Buffer contents written to file."); } catch (IOException e) { e.printStackTrace(System.err); } }