Java Code Examples for java.io.FileOutputStream

The following are top voted examples for showing how to use java.io.FileOutputStream. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: richfaces   File: ContainerInstaller.java View source code Vote up 9 votes
private void unzip(InputStream inputStream, File destination, boolean overwrite) {
    try {
        byte[] buf = new byte[1024];
        ZipInputStream zipinputstream = null;
        ZipEntry zipentry;
        zipinputstream = new ZipInputStream(inputStream);

        zipentry = zipinputstream.getNextEntry();
        while (zipentry != null) {
            int n;
            FileOutputStream fileoutputstream;
            File newFile = new File(destination, zipentry.getName());
            if (zipentry.isDirectory()) {
                newFile.mkdirs();
                zipentry = zipinputstream.getNextEntry();
                continue;
            }

            if (newFile.exists() && overwrite) {
                log.info("Overwriting " + newFile);
                newFile.delete();
            }

            fileoutputstream = new FileOutputStream(newFile);

            while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, n);
            }

            fileoutputstream.close();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();

        }

        zipinputstream.close();
    } catch (Exception e) {
        throw new IllegalStateException("Can't unzip input stream", e);
    }
}
 
Example 2
Project: my-ministry-assistant   File: FileUtils.java View source code Vote up 8 votes
public static void copyFile(File fromFile, File toFile) throws IOException {
	FileInputStream fromFileStream = new FileInputStream(fromFile);
	FileOutputStream toFileStream = new FileOutputStream(toFile);
	FileChannel fromChannel = fromFileStream.getChannel();
	FileChannel toChannel = toFileStream.getChannel();
	try {
		fromChannel.transferTo(0, fromChannel.size(), toChannel);
	} finally {
		if (fromChannel != null)
			fromChannel.close();
		if (toChannel != null)
			toChannel.close();

		fromFileStream.close();
		toFileStream.close();
	}
}
 
Example 3
Project: aws-toolkit-eclipse   File: TestToolManager.java View source code Vote up 7 votes
/**
 * Unzip the given file into the given directory.
 *
 * @param zipFile The zip file to unzip.
 * @param unzipped The directory to put the unzipped files into.
 * @throws IOException on file system error.
 */
private void unzip(final File zipFile, final File unzipped)
        throws IOException {

    ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile));
    try {

        ZipEntry entry;
        while ((entry = zip.getNextEntry()) != null) {
            Path path = new Path(entry.getName());

            File dest = new File(unzipped, path.toOSString());
            if (entry.isDirectory()) {
                if (!dest.mkdirs()) {
                    throw new RuntimeException(
                        "Failed to create directory while unzipping"
                    );
                }
            } else {
                FileOutputStream output = new FileOutputStream(dest);
                try {
                    IOUtils.copy(zip, output);
                } finally {
                    output.close();
                }
            }
        }

    } finally {
        zip.close();
    }
}
 
Example 4
Project: hacktoolkit-android_lib   File: FileUtils.java View source code Vote up 7 votes
public static int writeLines(Activity activity, String filename, ArrayList<String> lines) throws IOException {
	int linesWritten = 0;
	Context context = activity.getApplicationContext();
	try {
		FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
		for (String line : lines) {
			// add terminal character so that it doesn't get written as one line
			fos.write((line + "\n").getBytes());
			++linesWritten;
		}
		fos.close();
	} catch (FileNotFoundException fnfe) {
		fnfe.printStackTrace();
	}
	return linesWritten;
}
 
Example 5
Project: aws-toolkit-eclipse   File: RegionUtils.java View source code Vote up 7 votes
/**
 * Fetches a file from the URL given and writes it to the destination given.
 */
private static void fetchFile(String url, File destinationFile)
        throws IOException, ClientProtocolException, FileNotFoundException {

    HttpClient httpclient = HttpClientFactory.create(
            AwsToolkitCore.getDefault(), url);

    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if ( entity != null ) {
        InputStream instream = entity.getContent();
        FileOutputStream output = new FileOutputStream(destinationFile);
        try {
            int l;
            byte[] tmp = new byte[2048];
            while ( (l = instream.read(tmp)) != -1 ) {
                output.write(tmp, 0, l);
            }
        } finally {
            output.close();
            instream.close();
        }
    }
}
 
Example 6
Project: jentrata-msh   File: MessageRepository.java View source code Vote up 6 votes
public void persistMessage(AS2Message message) {
    if (!isDisabled && message!=null) {
        try {
            String type = message.isDispositionNotification()? DEFAULT_AS2_RECEIPT_TYPE:DEFAULT_AS2_MESSAGE_TYPE;
    
            PayloadCache cache = createPayloadCache(
                    message.getMessageID(), 
                    message.getFromPartyID(), 
                    message.getToPartyID(), 
                    type);
            
            FileOutputStream fos = new FileOutputStream(cache.getCache());
            message.writeTo(fos);
            fos.close();
            cache.checkIn();
        }
        catch (Exception e) {
            getModule().getLogger().warn("Unable to persist message to local repository", e);
        }
    }
}
 
Example 7
Project: apache-james-mime4j-groundhog   File: MimeStreamParserExampleMessagesTest.java View source code Vote up 6 votes
@Override
protected void runTest() throws Throwable {
    MimeStreamParser parser = null;
    TestHandler handler = null;
    MimeEntityConfig config = new MimeEntityConfig();
    config.setMaxLineLen(-1);
    parser = new MimeStreamParser(config);
    handler = new TestHandler();
    
    System.out.println("Parsing " + file.getName());
    parser.setContentHandler(handler);
    parser.parse(new FileInputStream(file));
    
    String result = handler.sb.toString();
    String xmlFile = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf('.')) + ".xml";
    String xmlFileMime4j = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf('.')) + ".mime4j.xml";
    
    try {
        String expected = IOUtils.toString(new FileInputStream(xmlFile), "ISO8859-1");
        assertEquals("Error parsing " + file.getName(), expected, result);
    } catch (FileNotFoundException e) {
        FileOutputStream fos = new FileOutputStream(xmlFileMime4j);
        fos.write(result.getBytes());
        fos.flush();
        fos.close();
        fail("XML file not found: generated a file with the expected result!");
    }
}
 
Example 8
Project: dlna   File: YouUtility.java View source code Vote up 6 votes
public static String getLastFrameBitmap(String url)  {
	try {
		Bitmap bitmap = null;
		bitmap = Player_UIManager.getBitmap();
		bitmap = Bitmap.createScaledBitmap(bitmap, 138, 93, false);
		File dir = new File(PALY_PATH);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		String imagePath = PALY_PATH + getMD5Str(url);
		File bitmapPath = new File(imagePath);
		
		FileOutputStream fOut = null;
		bitmapPath.createNewFile();
		
		fOut = new FileOutputStream(bitmapPath);
		bitmap.compress(Bitmap.CompressFormat.PNG, 75, fOut);
		
		fOut.flush();
		fOut.close();
		LOG.v("youUtility", "getLastFrameBitmap", "imagepath:"+imagePath);   
		return imagePath;
	} catch (Throwable e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 9
Project: netlib   File: HttpTestUtil.java View source code Vote up 6 votes
/**
 * Create the test file /tmp/testfile100000bytes.bin .
 * 
 * @throws Exception
 */
public void writeHttpTestFile() throws Exception {
    String FILENAME = "/tmp/testfile100000bytes.bin";
    FileOutputStream file = new FileOutputStream(FILENAME);
    file.write(HTTPTEST_TESTFILE_CONTENT_testfile100000bytes);
    file.close();
}
 
Example 10
Project: JAME   File: ChunkedFileOutputStream.java View source code Vote up 6 votes
/**
 * @see java.io.OutputStream#write(int)
 */
@Override
public void write(final int b) throws IOException {
	if (os == null) {
		os = new FileOutputStream(new File(path, prefix + chunk + suffix));
	}
	if (os != null) {
		os.write(b);
		length += 1;
		if ((length % chunkLength) == 0) {
			chunk += 1;
			os.close();
			os = null;
		}
	}
}
 
Example 11
Project: UnicentaPOS_AD   File: PrinterWritterFile.java View source code Vote up 6 votes
@Override
protected void internalWrite(byte[] data) {
    try {  
        if (m_out == null) {
            m_out = new FileOutputStream(m_sFilePrinter);  // No poner append = true.
        }
        m_out.write(data);
    } catch (IOException e) {
        System.err.println(e);
    }    
}
 
Example 12
Project: speechalyzer   File: Util.java View source code Vote up 6 votes
/**
 * <pre>
 * file 1 in 2 kopieren.
 * </pre>
 * 
 * @param in
 * @param out
 * @throws Exception
 */
public static void copyFile(File in, File out) throws Exception {
	FileInputStream fis = new FileInputStream(in);
	FileOutputStream fos = new FileOutputStream(out);
	byte[] buf = new byte[1024];
	int i = 0;
	while ((i = fis.read(buf)) != -1) {
		fos.write(buf, 0, i);
	}
	fis.close();
	fos.close();
}
 
Example 13
Project: cassandra-dev   File: FailureDetector.java View source code Vote up 6 votes
/**
 * Dump the inter arrival times for examination if necessary.
 */
public void dumpInterArrivalTimes()
{
    try
    {
        FileOutputStream fos = new FileOutputStream("/var/tmp/output-" + System.currentTimeMillis() + ".dat", true);
        fos.write(toString().getBytes());
        fos.close();
    }
    catch(Throwable th)
    {
        logger_.warn(LogUtil.throwableToString(th));
    }
}
 
Example 14
Project: transportlanguage   File: BytecodeCompilerTest.java View source code Vote up 6 votes
@Test
public void testProgram() throws Exception {
    // Define new program
    Program program = new Program("Countdown");

    // Define variables
    Variable var_i = Variable.create(Type.INT, "i", null);
    Variable var_zero = Variable.create(Type.INT, "zero", "0");
    Variable var_one = Variable.create(Type.INT, "one", "1");
    Variable var_continue = Variable.create(Type.BOOL, "continue", null);
    Variable var_stop = Variable.create(Type.BOOL, "stop", null);
    program.addVariable(var_i);
    program.addVariable(var_zero);
    program.addVariable(var_one);
    program.addVariable(var_continue);
    program.addVariable(var_stop);

    // Define function
    Function func_count = new Function("count", Type.INT, Type.INT);
    program.addFunction(func_count);

    func_count.getBody().add(new Output("", func_count.getVariables()[0]));
    func_count.getBody().add(new Return(var_zero));

    program.getBody().add(new Input("Count down from <int>: ", var_i));
    program.getBody().add(new Input("Stop at zero? <boolean>: ", var_stop));
    Application appl_stop = new Application(Operator.NOT, var_stop, var_stop);
    Application appl_continue = new Application(Operator.COMPGTE, var_i, var_zero, var_continue);
    Application appl_continue2 = new Application(Operator.OR, var_continue, var_stop, var_continue);
    program.getBody().add(appl_stop);
    program.getBody().add(appl_continue);
    program.getBody().add(appl_continue2);
    Loop loop_j = new Loop(var_continue);
    loop_j.getBody().add(new Call(func_count, var_i, var_zero));
    loop_j.getBody().add(new Application(Operator.SUBTRACTION, var_i, var_one, var_i));
    loop_j.getBody().add(appl_continue);
    loop_j.getBody().add(appl_continue2);
    program.getBody().add(loop_j);

    // Compile program
    // Tests for exceptions
    BytecodeCompiler compiler = new BytecodeCompiler(program);
    compiler.compileDebug();

    // Write to file for inspection
    FileOutputStream fos = new FileOutputStream(String.format("%s/%s.class", System.getProperty("java.io.tmpdir"), program.getId()));
    fos.write(compiler.asByteArray());
    fos.close();
}
 
Example 15
Project: android-simple-storage   File: AbstractDiskStorage.java View source code Vote up 6 votes
@Override
public void appendFile(String directoryName, String fileName, byte[] bytes) {
	if (!isFileExist(directoryName, fileName)) {
		throw new RuntimeException("Impossible to append content, because such file doesn't exist");
	}

	try {
		String path = buildPath(directoryName, fileName);
		FileOutputStream stream = new FileOutputStream(new File(path), true);
		stream.write(bytes);
		stream.write(System.getProperty("line.separator").getBytes());
		stream.flush();
		stream.close();
	} catch (IOException e) {
		throw new RuntimeException("Failed to append content to file", e);
	}
}
 
Example 16
Project: extFM-Tooling   File: YMSTransformation.java View source code Vote up 6 votes
public void writeFile(File file, final Object object) {
	FileOutputStream fop = null;
	ByteArrayOutputStream out = new ByteArrayOutputStream();

	try {
		fop = new FileOutputStream(file);
	} catch (FileNotFoundException e1) {
		e1.printStackTrace();
	}
	Marshaller m;
	try {
		m = Context.getInstance().getJAXBContext().createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
		m.marshal(object, out);
		fop.write(out.toByteArray());
		fop.flush();
		fop.close();
	} catch (JAXBException | IOException e) {
		e.printStackTrace();
	}
	// get the content in bytes
	System.out.println("Done");
}
 
Example 17
Project: jentrata-msh   File: PropertyMap.java View source code Vote up 6 votes
/**
 * Stores the properties to the specified url location.
 * 
 * @param url the url of the properties source.
 * @throws Exception if the operation is unsuccessful. 
 * @see hk.hku.cecid.piazza.commons.module.PersistentComponent#storing(java.net.URL)
 */
protected void storing(URL url) throws Exception {
    FileOutputStream fos = new FileOutputStream(Convertor.toFile(url));
    props.store(fos, "Properties saved automatically by "
            + getClass().getName());
    fos.flush();
    fos.close();
}
 
Example 18
Project: richfaces   File: UserPrefsHelper.java View source code Vote up 6 votes
/**
 * Convenience method invoked after user add avatar and outject avatar to conversation
 *
 * param event - upload event
 */
public void uploadAvatar(FileUploadEvent event) {
    UploadedFile file = event.getUploadedFile();
    try {
        File f = new File((file.getName() + "avatar"));

        if (!f.exists()) {
            f.createNewFile();
        }

        FileOutputStream fos = new FileOutputStream(f);
        fos.write(file.getData());
        fos.flush();
        fos.close();

        avatarData = f;
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}
 
Example 19
Project: aipo   File: MergeFiles.java View source code Vote up 6 votes
public void writeToFile() throws FileNotFoundException, IOException
{
    FileOutputStream writer = null;
    try
    {
        writer = new FileOutputStream(dest_file);
    }
    catch (FileNotFoundException ex)
    {
        File file = new File(dest_file);
        writer = new FileOutputStream(file.getPath(), false);
    }
    writer.flush();
    for (int i = 0; i < baseArray.size(); i++)
    {
        if(verbose)
            System.out.println("While writing baseArray["+i+"] = " + baseArray.get(i));
        writer.write(((String)baseArray.get(i)).getBytes());
        writer.write(lineSeparator.getBytes());
        writer.flush();
    }
    writer.close();

}
 
Example 20
Project: cardslib   File: BitmapUtils.java View source code Vote up 6 votes
/**
 * Creates a File from a Bitmap
 *
 * @param bitmap to convert in a file
 *
 * @return File
 */
public static File createFileFromBitmap(Bitmap bitmap) {

    if (bitmap == null) return null;

    File photoFile=null;

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
    File photoStorage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    if (photoStorage!=null){
        photoFile = new File(photoStorage, (System.currentTimeMillis()) + ".png");
        try {
            //f.createNewFile();
            FileOutputStream fo = new FileOutputStream(photoFile);
            fo.write(bytes.toByteArray());
            fo.flush();
            fo.close();
        } catch (IOException e) {
            Log.e(TAG, "Error saving image ", e);
        }
    }

    return photoFile;
}
 
Example 21
Project: faint   File: Utilities.java View source code Vote up 6 votes
/**
  * Writes the contents of the entry at the given url to the given file.
  *
  * @param url The url to get
  * @param destinationFile The file to write to
  * @throws IOException if something goes wrong
  */
 public static void saveFileFromURL(URL url, File destinationFile) throws IOException{
	FileOutputStream fo = new FileOutputStream(destinationFile);
	InputStream is = url.openStream();
	
	byte[] data = new byte[1024];
	int bytecount = 0;
	do {
		fo.write(data, 0, bytecount);
		bytecount = is.read(data);
	} while (bytecount > 0);
	
	fo.flush();
	fo.close();
}
 
Example 22
Project: Magnolia   File: ContentUtil.java View source code Vote up 6 votes
/**
 * Session based copy operation. As JCR only supports workspace based copies this operation is performed
 * by using export import operations.
 */
public static void copyInSession(Content src, String dest) throws RepositoryException {
    final String destParentPath = StringUtils.defaultIfEmpty(StringUtils.substringBeforeLast(dest, "/"), "/");
    final String destNodeName = StringUtils.substringAfterLast(dest, "/");
    final Session session = src.getWorkspace().getSession();
    try{
        final File file = File.createTempFile("mgnl", null, Path.getTempDirectory());
        final FileOutputStream outStream = new FileOutputStream(file);
        session.exportSystemView(src.getHandle(), outStream, false, false);
        outStream.flush();
        IOUtils.closeQuietly(outStream);
        FileInputStream inStream = new FileInputStream(file);
        session.importXML(
                destParentPath,
                inStream,
                ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
        IOUtils.closeQuietly(inStream);
        file.delete();
        if(!StringUtils.equals(src.getName(), destNodeName)){
            String currentPath;
            if(destParentPath.equals("/")){
                currentPath = "/" + src.getName();
            }
            else{
                currentPath = destParentPath + "/" + src.getName();
            }
            session.move(currentPath, dest);
        }
    }
    catch (IOException e) {
        throw new RepositoryException("Can't copy node " + src + " to " + dest, e);
    }
}
 
Example 23
Project: QEditor   File: TedActivity.java View source code Vote up 6 votes
/**
 * Write String to File
 * 
 * @param filePath path of file to write to
 * @param data String to write to file
 */
public void writeToFile(String filePath, String data) {
	try {
		FileOutputStream fOut = new FileOutputStream(filePath);
		fOut.write(data.getBytes());
		fOut.flush();
		fOut.close();
	}
	catch (IOException iox) {
		iox.printStackTrace();
	}

}
 
Example 24
Project: NoRefreshToggle   File: AndroSS.java View source code Vote up 6 votes
private boolean writeScreenshot(Bitmap bmp, String filename) {
    boolean success = false;

    File output = new File(AndroSS.output_dir + filename);
    try {
        // A little wasteful, maybe, but this avoids errors due to the
        // output dir not existing.
        output.getParentFile().mkdirs();
        FileOutputStream os = new FileOutputStream(output);
        switch (getCompressionType()) {
        case PNG:
            success = bmp.compress(Bitmap.CompressFormat.PNG, 0, os);
            break;
        case JPG_HQ:
            success = bmp.compress(Bitmap.CompressFormat.JPEG, 90, os);
            break;
        case JPG_FAST:
            success = bmp.compress(Bitmap.CompressFormat.JPEG, 40, os);
        }
        os.flush();
        os.close();
    } catch (FileNotFoundException fnfe) {
    } catch (IOException ioe) {}

    return success;
}
 
Example 25
Project: xface-android   File: XFileUtils.java View source code Vote up 6 votes
/**
 * ???
 *
 * @param filePath
 *            ?????????
 * @param data
 *            ??????
 * @return ?????????
 */
public static long write(String fileName, String data, int position)
        throws FileNotFoundException, IOException {
    boolean append = false;
    if (position > 0) {
        truncateFile(fileName, position);
        append = true;
    }

    byte[] rawData = data.getBytes();
    ByteArrayInputStream in = new ByteArrayInputStream(rawData);
    FileOutputStream out = new FileOutputStream(fileName, append);
    byte buff[] = new byte[rawData.length];
    in.read(buff, 0, buff.length);
    out.write(buff, 0, rawData.length);
    out.flush();
    out.close();

    return data.length();
}
 
Example 26
Project: android-simple-storage   File: AbstractDiskStorage.java View source code Vote up 6 votes
@Override
public void copy(File file, String directoryName, String fileName) {
	if (!file.isFile()) {
		return;
	}
	
	FileInputStream inStream = null;
	FileOutputStream outStream = null;
	try {
		inStream = new FileInputStream(file);
		outStream = new FileOutputStream(new File(buildPath(directoryName, fileName)));
		FileChannel inChannel = inStream.getChannel();
		FileChannel outChannel = outStream.getChannel();
		inChannel.transferTo(0, inChannel.size(), outChannel);
	} catch (Exception e) {
		throw new StorageException(e);
	} finally {
		closeQuietly(inStream);
		closeQuietly(outStream);
	}
}
 
Example 27
Project: afwall   File: MultiProfilePreferenceFragment.java View source code Vote up 6 votes
public void copy(File src, File dst) throws IOException {
	FileInputStream inStream = new FileInputStream(src);
	FileOutputStream outStream = new FileOutputStream(dst);
	FileChannel inChannel = inStream.getChannel();
	FileChannel outChannel = outStream.getChannel();
	inChannel.transferTo(0, inChannel.size(), outChannel);
	inStream.close();
	outStream.close();
}
 
Example 28
Project: eclipse-integration-commons   File: FileUtil.java View source code Vote up 6 votes
public static void copy(File source, File target) throws IOException {
	FileInputStream sourceOutStream = new FileInputStream(source);
	FileOutputStream targetOutStream = new FileOutputStream(target);
	FileChannel sourceChannel = sourceOutStream.getChannel();
	FileChannel targetChannel = targetOutStream.getChannel();
	sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
	sourceChannel.close();
	targetChannel.close();
	sourceOutStream.close();
	targetOutStream.close();
}
 
Example 29
Project: OSM2World   File: ImageExporter.java View source code Vote up 6 votes
private void writeHeader() throws IOException {
	
	out = new FileOutputStream(outputFile);
			
	// write header	
	Charset charSet = Charset.forName("US-ASCII");
	out.write("P6\n".getBytes(charSet));
	out.write(String.format("%d %d\n", cols, rows).getBytes(charSet));
	out.write("255\n".getBytes(charSet));

	fc = out.getChannel();			
}
 
Example 30
Project: MP4ParserMergeAudioVideo   File: MainActivity.java View source code Vote up 6 votes
private boolean subTitle() {
	try {
		// ????????????
		String filePath = Environment.getExternalStorageDirectory() + "/sample1.mp4";
		Movie countVideo = MovieCreator.build(filePath);

		// SubTitle???
		TextTrackImpl subTitleEng = new TextTrackImpl();
		subTitleEng.getTrackMetaData().setLanguage("eng");

		subTitleEng.getSubs().add(new TextTrackImpl.Line(0, 1000, "Five"));
		subTitleEng.getSubs().add(new TextTrackImpl.Line(1000, 2000, "Four"));
		subTitleEng.getSubs().add(new TextTrackImpl.Line(2000, 3000, "Three"));
		subTitleEng.getSubs().add(new TextTrackImpl.Line(3000, 4000, "Two"));
		subTitleEng.getSubs().add(new TextTrackImpl.Line(4000, 5000, "one"));
		countVideo.addTrack(subTitleEng);

		// ??
		Container container = new DefaultMp4Builder().build(countVideo);
		String outputFilePath = Environment.getExternalStorageDirectory() + "/output_subtitle.mp4";
		FileOutputStream fos = new FileOutputStream(outputFilePath);
		FileChannel channel = fos.getChannel();
		container.writeContainer(channel);
		fos.close();
	} catch (Exception e) {
		e.printStackTrace();
		return false;
	}
	return true;
}
 
Example 31
Project: krypton   File: EmbeddedEquinoxLauncher.java View source code Vote up 6 votes
private void extractAndClose(InputStream in, FileOutputStream out, long size) throws IOException, FileNotFoundException {
	FileChannel outChannel = null;
	ReadableByteChannel inChannel = null;
	try {
		inChannel = Channels.newChannel(in);
		outChannel = out.getChannel();
		outChannel.transferFrom(inChannel, 0, size);
	} finally {
		if (outChannel != null) {
			outChannel.close();
		}
		if (inChannel != null) {
			inChannel.close();
		}
	}
}
 
Example 32
Project: Field-Book   File: DataHelper.java View source code Vote up 6 votes
/**
 * Helper function to copy database
 */
public static void copyFileCall(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
    FileChannel fromChannel = null;
    FileChannel toChannel = null;

    try {
        fromChannel = fromFile.getChannel();
        toChannel = toFile.getChannel();
        fromChannel.transferTo(0, fromChannel.size(), toChannel);
    } finally {
        try {
            if (fromChannel != null) {
                fromChannel.close();
            }
        } finally {
            if (toChannel != null) {
                toChannel.close();
            }
        }
    }
}
 
Example 33
Project: gundog-engine   File: DownloadManager.java View source code Vote up 6 votes
@Override
public Integer call() {
	try {
		long startTime = System.currentTimeMillis();

		String basePath = ASSETS[loc][0];
		String fileName = ASSETS[loc][1];

		String urlName = hostname + "assets/" + basePath + fileName;

		Modules.LOG.info(TAG, "Downloading " + urlName);

		String path = FILE_SYSTEM_PATH + basePath;
		new File(path).mkdirs();
		path += fileName;
		Modules.LOG.info(TAG, "Storing " + fileName + " at " + path);
		FileOutputStream stream = new FileOutputStream(path, false);
		FileChannel fileChannel = stream.getChannel();

		URL url = new URL(urlName);
		URLConnection openConnection = url.openConnection();
		openConnection.setUseCaches(false);
		openConnection.setDoOutput(false);
		ReadableByteChannel inChannel = Channels.newChannel(openConnection.getInputStream());

		long read = 0;
		long pos = 0;
		while ((read = fileChannel.transferFrom(inChannel, pos, ASSET_SIZES[loc])) >= 0
				&& pos < ASSET_SIZES[loc]) {
			pos += read;
			currentAssetSize.addAndGet(read);
		}
		inChannel.close();
		fileChannel.close();
		stream.close();

		File file = new File(path);
		if (ASSET_SIZES[loc] != file.length()) {
			file.delete();
			Modules.LOG.error(TAG, "Failed to download " + fileName + " correctly");
			return loc;
		}

		Modules.LOG.info(TAG, "wrote file in " + (System.currentTimeMillis() - startTime) + " msec");
		return SUCCESSFUL;
	} catch (Exception e) {
		Modules.LOG.error(TAG, "Error downloading file: " + e.toString());
		return 0;
	}
}
 
Example 34
Project: dataverse   File: FileAccessIO.java View source code Vote up 6 votes
@Override
public Channel openAuxChannel(String auxItemTag, DataAccessOption... options) throws IOException {

    Path auxPath = getAuxFilePath(auxItemTag);

    if (isWriteAccessRequested(options)) {
        FileOutputStream auxOut = new FileOutputStream(auxPath.toFile());

        if (auxOut == null) {
            throw new IOException("Failed to open Auxiliary File " + this.getDataFile().getStorageIdentifier() + "." + auxItemTag + " for writing.");
        }

        return auxOut.getChannel();
    }
    
    // Read access requested.
    // Check if this Aux object is cached; and if so, open for reading:

    if (!auxPath.toFile().exists()) {
        throw new FileNotFoundException("Auxiliary File " + this.getDataFile().getStorageIdentifier() + "." + auxItemTag + " does not exist.");
    }

    FileInputStream auxIn = new FileInputStream(auxPath.toFile());

    if (auxIn == null) {
        throw new IOException("Failed to open Auxiliary File " + this.getDataFile().getStorageIdentifier() + "." + auxItemTag + " for reading");
    }

    return auxIn.getChannel();

}
 
Example 35
Project: Hungry   File: FileUtils.java View source code Vote up 6 votes
/**
 * Internal copy file method.
 * 
 * @param srcFile  the validated source file, must not be <code>null</code>
 * @param destFile  the validated destination file, must not be <code>null</code>
 * @param preserveFileDate  whether to preserve the file date
 * @throws IOException if an error occurs
 */
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        input  = fis.getChannel();
        output = fos.getChannel();
        long size = input.size();
        long pos = 0;
        long count = 0;
        while (pos < size) {
            count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos);
            pos += output.transferFrom(input, pos, count);
        }
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(fis);
    }

    if (srcFile.length() != destFile.length()) {
        throw new IOException("Failed to copy full contents from '" +
                srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
        destFile.setLastModified(srcFile.lastModified());
    }
}
 
Example 36
Project: FTL-Hyperion   File: datLib.java View source code Vote up 6 votes
public void Extract(int IndexID, String ExtractPath) {
	if (this.Stored(IndexID)) {
		datItem II = this.ItemIndex.get(IndexID);
		File file = new File(ExtractPath);
		this.mkdir(new File(ExtractPath).getParent());
		try {
			FileOutputStream out = new FileOutputStream(ExtractPath, true);
			try {
				FileChannel ch = out.getChannel();
				ch.write(this.Read(II.DataOffset, II.DataSize));
			} finally {
				out.close();
			} 
		} catch (Exception ex) { }
	}
}
 
Example 37
Project: TweetTopics2.0   File: FileUtils.java View source code Vote up 6 votes
public static void copy(String source, String destiny) throws IOException {
    try
    {
        FileInputStream fis = new FileInputStream(source);
        FileOutputStream fos = new FileOutputStream(destiny);
        FileChannel channelSource = fis.getChannel();
        FileChannel channelDestiny = fos.getChannel();
        channelSource.transferTo(0, channelSource.size(), channelDestiny);
        fis.close();
        fos.close();
    }
    catch(Exception e)
    {
        Log.d(Utils.TAG, e.getClass().getName());
    }
}
 
Example 38
Project: netty3.9-note   File: AbstractMemoryHttpData.java View source code Vote up 6 votes
public boolean renameTo(File dest) throws IOException {
    if (dest == null) {
        throw new NullPointerException("dest");
    }
    if (channelBuffer == null) {
        // empty file
        dest.createNewFile();
        isRenamed = true;
        return true;
    }
    int length = channelBuffer.readableBytes();
    FileOutputStream outputStream = new FileOutputStream(dest);
    FileChannel fileChannel = outputStream.getChannel();
    ByteBuffer byteBuffer = channelBuffer.toByteBuffer();
    int written = 0;
    while (written < length) {
        written += fileChannel.write(byteBuffer);
    }
    fileChannel.force(false);
    fileChannel.close();
    outputStream.close();
    isRenamed = true;
    return written == length;
}
 
Example 39
Project: explor   File: FileIO.java View source code Vote up 6 votes
/**
 * Write the data to the file indicate by fileName. The file is created
 * if it doesn't exist.
 * 
 * @param activity
 * @param data
 * @param fileName
 * @throws IOException
 */
public static void write(
        Activity activity, String data, String fileName)
        throws IOException {
    FileOutputStream fo = activity.openFileOutput(fileName, 0);
    BufferedWriter bf = new BufferedWriter(new FileWriter(fo.getFD()));
    bf.write(data);
    bf.flush();
    bf.close();
}
 
Example 40
Project: property-db   File: BackupTestActivity.java View source code Vote up 6 votes
void run() {
    try {
        writeFile("a", "a\naa", MODE_PRIVATE);
        writeFile("empty", "", MODE_PRIVATE);

        ParcelFileDescriptor state = ParcelFileDescriptor.open(
                new File(getFilesDir(), "state"),
                ParcelFileDescriptor.MODE_READ_WRITE|ParcelFileDescriptor.MODE_CREATE|
                ParcelFileDescriptor.MODE_TRUNCATE);
        FileBackupHelper h = new FileBackupHelper(BackupTestActivity.this,
                new String[] { "a", "empty" });
        FileOutputStream dataFile = openFileOutput("backup_test", MODE_WORLD_READABLE);
        BackupDataOutput data = new BackupDataOutput(dataFile.getFD());
        h.performBackup(null, data, state);
        dataFile.close();
        state.close();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 41
Project: GeoGig   File: FileRefDatabase.java View source code Vote up 6 votes
/**
 * @param refName the full name of the ref (e.g.
 *        [email protected] refs/heads/master, HEAD, transaction/<tx id>/refs/orig/refs/heads/master, etc.}
 * @param refValue
 */
private void store(String refName, String refValue) {
    final File refFile = toFile(refName);
    try {
        synchronized (refFile.getCanonicalPath().intern()) {
            Files.createParentDirs(refFile);
            checkState(refFile.exists() || refFile.createNewFile(),
                    "Unable to create file for ref %s", refFile);

            FileOutputStream fout = new FileOutputStream(refFile);
            try {
                FileDescriptor fd = fout.getFD();
                fout.write((refValue + "\n").getBytes(CHARSET));
                fout.flush();
                // force change to be persisted to disk
                fd.sync();
            } finally {
                fout.close();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw Throwables.propagate(e);
    }
}
 
Example 42
Project: google-libs-for-android   File: FileCacheRequest.java View source code Vote up 6 votes
@Override
public OutputStream getBody() throws IOException {
    if (mOutputStream != null) {
        return mOutputStream;
    }
    // Create a file Output stream
    File temp = createTempFile(mFile);
    try {
        FileOutputStream fileOutput = new FileOutputStream(temp);
        FileDescriptor fd = fileOutput.getFD();
        OutputStream output = fileOutput;
        try {
            output = new BufferedOutputStream(output, BUFFER_SIZE);

            // Write the HTTP headers
            DataOutputStream dout = new DataOutputStream(output);
            writeHeaders(dout);

            mOutputStream = new TempFileOutputStream(dout, fd, temp, mFile);
            return mOutputStream;
        } finally {
            if (mOutputStream == null) {
                // The return-statement was not reached
                output.close();
            }
        }
    } finally {
        if (mOutputStream == null) {
            // The return-statement was not reached
            temp.delete();
        }
    }
}
 
Example 43
Project: android-flash-card   File: FileIO.java View source code Vote up 6 votes
/**
 * Write the data to the file indicate by fileName. The file is created
 * if it doesn't exist.
 * 
 * @param activity
 * @param data
 * @param fileName
 * @throws IOException
 */
public static void write(
        Activity activity, String data, String fileName)
        throws IOException {
    FileOutputStream fo = activity.openFileOutput(fileName, 0);
    BufferedWriter bf = new BufferedWriter(new FileWriter(fo.getFD()));
    bf.write(data);
    bf.flush();
    bf.close();
}
 
Example 44
Project: open-mika   File: jdk11.java View source code Vote up 6 votes
public void test (TestHarness testharness)
 {
   TestHarness harness = testharness;
   harness.setclass("java.io.FileWriter");
   try {
     FileWriter fr1 = new FileWriter("tmpfile");
  harness.check(true, "FileWriter(string)");
     FileWriter fr1a = new FileWriter("tmpfile", true);
  harness.check(true, "FileWriter(string, boolean)");
  File f2 = new File("tmpfile");
     FileWriter fr2 = new FileWriter(f2);
  harness.check(true, "FileWriter(File)");
  FileOutputStream fis = new FileOutputStream(f2);
  FileWriter fr3 = new FileWriter(fis.getFD());
  harness.check(true, "FileWriter(FileDescriptor)");
   }
   catch (IOException e) {
     harness.fail("Can't open file 'choices'");
   } 
}
 
Example 45
Project: Assassins-Test   File: FileIO.java View source code Vote up 6 votes
/**
 * Write the data to the file indicate by fileName. The file is created
 * if it doesn't exist.
 * 
 * @param activity
 * @param data
 * @param fileName
 * @throws IOException
 */
public static void write(
        Activity activity, String data, String fileName)
        throws IOException {
    FileOutputStream fo = activity.openFileOutput(fileName, 0);
    BufferedWriter bf = new BufferedWriter(new FileWriter(fo.getFD()));
    bf.write(data);
    bf.flush();
    bf.close();
}
 
Example 46
Project: Brink   File: FileIO.java View source code Vote up 6 votes
/**
 * Write the data to the file indicate by fileName. The file is created
 * if it doesn't exist.
 * 
 * @param activity
 * @param data
 * @param fileName
 * @throws IOException
 */
public static void write(
        Activity activity, String data, String fileName)
        throws IOException {
    FileOutputStream fo = activity.openFileOutput(fileName, 0);
    BufferedWriter bf = new BufferedWriter(new FileWriter(fo.getFD()));
    bf.write(data);
    bf.flush();
    bf.close();
}
 
Example 47
Project: JPaxos   File: SynchronousClientBatchStore.java View source code Vote up 6 votes
protected SynchronousClientBatchStore() {
    super();

    try {
        String logPath = processDescriptor.logPath + '/' + processDescriptor.localId;
        File logDir = new File(logPath);
        logDir.mkdirs();

        Pattern pattern = Pattern.compile("batches\\.(\\d+)\\.log");
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        for (String fileName : logDir.list()) {
            Matcher matcher = pattern.matcher(fileName);
            if (matcher.find()) {
                int x = Integer.parseInt(matcher.group(1));
                numbers.add(x);
            }
        }
        Collections.sort(numbers);

        for (Integer number : numbers) {
            DataInputStream dis = new DataInputStream(new FileInputStream(new File(logDir,
                    "batches." + number + ".log")));
            load(dis);
        }

        logger.info("Loaded batch store files");

        int newFileId;
        if (numbers.isEmpty()) {
            newFileId = 0;
        } else {
            newFileId = numbers.get(numbers.size() - 1) + 1;
        }

        FileOutputStream fis = new FileOutputStream(new File(logDir, "batches." + newFileId +
                                                                     ".log"));

        fd = fis.getFD();

        file = new DataOutputStream(fis);

    } catch (Exception e) {
        throw new RuntimeException("Could not read batch values or start new file!", e);
    }
}
 
Example 48
Project: hadoop-20   File: BlockDataFile.java View source code Vote up 6 votes
public synchronized Writer getWriter(int bufferSize)
    throws FileNotFoundException, IOException {
  if (file == null) {
    throw new IOException("file is NULL");
  }
  FileOutputStream fout = new FileOutputStream(
      new RandomAccessFile(file, "rw").getFD());
  FileChannel channel = fout.getChannel();
  FileDescriptor fd = fout.getFD();
  OutputStream dataOut;
  if (bufferSize > 0) {
    dataOut = new BufferedOutputStream(fout, bufferSize);
  } else {
    dataOut = fout;
  }
  return new Writer(dataOut, channel, fd);
}
 
Example 49
Project: android-15   File: BackupTestActivity.java View source code Vote up 6 votes
void run() {
    try {
        writeFile("a", "a\naa", MODE_PRIVATE);
        writeFile("empty", "", MODE_PRIVATE);

        ParcelFileDescriptor state = ParcelFileDescriptor.open(
                new File(getFilesDir(), "state"),
                ParcelFileDescriptor.MODE_READ_WRITE|ParcelFileDescriptor.MODE_CREATE|
                ParcelFileDescriptor.MODE_TRUNCATE);
        FileBackupHelper h = new FileBackupHelper(BackupTestActivity.this,
                new String[] { "a", "empty" });
        FileOutputStream dataFile = openFileOutput("backup_test", MODE_WORLD_READABLE);
        BackupDataOutput data = new BackupDataOutput(dataFile.getFD());
        h.performBackup(null, data, state);
        dataFile.close();
        state.close();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 50
Project: Protocoder   File: FileIO.java View source code Vote up 6 votes
/**
 * Write the data to the file indicate by fileName. The file is created if
 * it doesn't exist.
 */
public static void write(Activity activity, String data, String fileName) throws IOException {
	FileOutputStream fo = activity.openFileOutput(fileName, 0);
	BufferedWriter bf = new BufferedWriter(new FileWriter(fo.getFD()));
	bf.write(data);
	bf.flush();
	bf.close();
}
 
Example 51
Project: walkitalkie   File: TalkActivity.java View source code Vote up 6 votes
private void startRecording() throws IllegalStateException, IOException {
 // Use a filedescriptor instead of direct file
 // This will enable easy transition to sockets later
 mFileOut = new FileOutputStream(mFileName);
 mFD = mFileOut.getFD();
 
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mRecorder.setOutputFile(mFD);
    mRecorder.prepare();
    mRecorder.start(); 
}
 
Example 52
Project: android-sdk-sources-for-api-level-23   File: BackupTestActivity.java View source code Vote up 6 votes
void run() {
    try {
        writeFile("a", "a\naa", MODE_PRIVATE);
        writeFile("empty", "", MODE_PRIVATE);

        ParcelFileDescriptor state = ParcelFileDescriptor.open(
                new File(getFilesDir(), "state"),
                ParcelFileDescriptor.MODE_READ_WRITE|ParcelFileDescriptor.MODE_CREATE|
                ParcelFileDescriptor.MODE_TRUNCATE);
        FileBackupHelper h = new FileBackupHelper(BackupTestActivity.this,
                new String[] { "a", "empty" });
        FileOutputStream dataFile = openFileOutput("backup_test", MODE_WORLD_READABLE);
        BackupDataOutput data = new BackupDataOutput(dataFile.getFD());
        h.performBackup(null, data, state);
        dataFile.close();
        state.close();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 53
Project: SimpleRep   File: BinaryStableStorage.java View source code Vote up 6 votes
protected void openStreams() throws IOException {
	FileOutputStream fo1 = new FileOutputStream(logFile1, true);
	FileOutputStream fo2 = new FileOutputStream(logFile2, true);
	o1 = new DataOutputStream(fo1);
	o2 = new DataOutputStream(fo2);
	fd1 = fo1.getFD();
	fd2 = fo2.getFD();
}
 
Example 54
Project: FeedMeAndroid   File: FileIO.java View source code Vote up 6 votes
/**
 * Write the data to the file indicate by fileName. The file is created
 * if it doesn't exist.
 * 
 * @param activity
 * @param data
 * @param fileName
 * @throws IOException
 */
public static void write(
        Activity activity, String data, String fileName)
        throws IOException {
    FileOutputStream fo = activity.openFileOutput(fileName, 0);
    BufferedWriter bf = new BufferedWriter(new FileWriter(fo.getFD()));
    bf.write(data);
    bf.flush();
    bf.close();
}
 
Example 55
Project: Gui2Go   File: ProjectXMLParser.java View source code Vote up 5 votes
public void CreateNewProjectXML(ProjectInfo project, ActivityInfo activity) {
    XmlSerializer serializer = Xml.newSerializer();
    File newxmlfile;
    FileOutputStream fileos;

    String sdState = android.os.Environment.getExternalStorageState();
    String path;
    if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
        path = Environment.getExternalStorageDirectory().getAbsolutePath();
    } else {
        Toast.makeText(context, "No SD card available!",
                        Toast.LENGTH_SHORT).show();
        return;
    }
    
    path += "/Gui2Go/Projects/" + project.name + "/";

    // create the project folder
    try {
        newxmlfile = new File(path);
        newxmlfile.mkdirs(); // make the folder path
        newxmlfile = new File(path + "Images/");
        newxmlfile.mkdirs(); // make the images folder
        path += project.name + ".xml";
        newxmlfile = new File(path);
        newxmlfile.createNewFile(); // make the project XML file
        fileos = new FileOutputStream(newxmlfile);

        serializer.setOutput(fileos, "utf-8");
        serializer.startDocument(null, null);
        serializer.setFeature(
                        "http://xmlpull.org/v1/doc/features.html#indent-output",
                        true);

        serializer.startTag(null, "Project");
        serializer.attribute(null, "name", project.name);
        serializer.attribute(null, "targetSDK", project.targetSDK);
        serializer.attribute(null, "mainActivity", project.mainActivityName);
        if (project.author != null) {
            serializer.attribute(null, "author", project.author);
        }
        serializer.startTag(null, "Activity");
        serializer.attribute(null, "name", activity.name);
        serializer.attribute(null, "screenSize", activity.screenSize);
        serializer.endTag(null, "Activity");
        serializer.endTag(null, "Project");
        serializer.endDocument();
        // write xml data into the FileOutputStream
        serializer.flush();
        // finally we close the file stream
        fileos.close();

        Toast.makeText(context,
                        "Created new project called " + project.name + "!",
                        Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(context, "Couldn't create project file!",
                        Toast.LENGTH_SHORT).show();
        // Log.d("CreateNewProjectXML", e.getMessage());
    }
}
 
Example 56
Project: dlna   File: YouUtility.java View source code Vote up 5 votes
/**
 * ????
 * 
 * @param fromFilePath
 *            ?????
 * @param toFilePath
 *            ??????
 */
public static void copyFile(String fromFilePath, String toFilePath) {
	
	String status = Environment.getExternalStorageState();
	if(!status.equals(Environment.MEDIA_MOUNTED)) {
		return;
	}
	File toFile = new File(toFilePath);
	if (toFile.exists()) {
		toFile.delete();
	}
	
	if(fromFilePath == null) {
		return;
	}
	
	File fromFile = new File(fromFilePath);
	if (!fromFile.exists()) {
		return;
	}

	if (!fromFile.isFile()) {
		return;
	}

	if (!fromFile.canRead()) {
		return;
	}

	if (!toFile.getParentFile().exists()) {
		toFile.getParentFile().mkdirs();
	}

	try {

		FileInputStream fosfrom = new FileInputStream(fromFile);

		FileOutputStream fosto = new FileOutputStream(toFile);

		byte bt[] = new byte[1024];

		int c;

		while ((c = fosfrom.read(bt)) > 0) {

			fosto.write(bt, 0, c); // ??????????

		}
		fosfrom.close();
		fosto.close();
	} catch (Exception ex) {
		LOG.e(TAG,"copyFile", ex.getMessage());
	}
}
 
Example 57
Project: BioWiki   File: CachedDownloader.java View source code Vote up 5 votes
public void downloadFromUrl(String DownloadUrl, String fileName, String fileType) {

        try {

            File dir = new File(root.getAbsolutePath() + "/" + fileType);
            if (dir.exists() == false) {
                dir.mkdirs();
            }

            URL url = new URL(DownloadUrl); //you can write here any link
            File file = new File(dir, fileName);

            long startTime = System.currentTimeMillis();
            Log.d("DownloadManager", "download beginning");
            Log.d("DownloadManager", "download url:" + url);
            Log.d("DownloadManager", "downloaded file name:" + fileName);

           /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

           /*
            * Define InputStreams to read from the URLConnection.
            */
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

           /*
            * Read bytes to the Buffer until there is nothing more to read(-1).
            */
            ByteArrayBuffer baf = new ByteArrayBuffer(5000);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }


           /* Convert the Bytes read to a String. */
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.flush();
            fos.close();

            File UAG = new File(dir, "." + fileName);
            UAG.createNewFile();

            Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");

        } catch (IOException e) {
            Log.d("DownloadManager", "Error: " + e);
        }

    }
 
Example 58
Project: java-csp   File: CSPNative.java View source code Vote up 5 votes
private boolean loadLibrary(String nativePath, String path) {
		URL url = CSPNative.class.getClassLoader().getResource(path);
		LOGGER.debug("url = {}",url);

		if (url == null) {
			return false;
		}

		File file = new File(url.getPath());

		if (file.canRead()) {
//			return loadFromPath(file.getAbsolutePath());
			System.load(file.getAbsolutePath());
			return true;
		}

		OutputStream os = null;
		InputStream is = null;
		boolean createTempFile = nativePath == null || nativePath.isEmpty();

		try {
			
			if(createTempFile) {
				file = File.createTempFile("java-csp-provider", "");
				file.deleteOnExit();
			}
			else {
				file = new File(nativePath, path);
				File parent = file.getParentFile();
				if(!parent.exists())
					parent.mkdirs();
			}
			LOGGER.debug("file = {}", file);

			is = url.openStream();
			os = new FileOutputStream(file);

			try {
				byte buffer[] = new byte[128 * 1024];

				int read = is.read(buffer);

				while (read > 0) {
					os.write(buffer, 0, read);
					read = is.read(buffer);
				}
				os.flush();
			}
			finally {
				closeSilently(os);
				closeSilently(is);
				
				os = null;
				is = null;
			}
			System.load(file.getAbsolutePath());

			return true;
		} catch (IOException e) {
			throw new RuntimeException("Unable to load native library.", e);
		} finally {
			if (createTempFile && file != null) {
				file.delete();
			}
			closeSilently(os);
			closeSilently(is);
		}
	}
 
Example 59
Project: android-platform-tools-base   File: Main.java View source code Vote up 5 votes
static public void dumpDirectory(FsDirectory dir, int tabStop, File curDirectory) throws IOException {
    Iterator<FsDirectoryEntry> i = dir.iterator();
    while (i.hasNext()) {
        final FsDirectoryEntry e = i.next();
        if (e.isDirectory()) {
            for (int idx = 0; idx < tabStop; idx++)
                System.out.print(' ');
            if (e.getName().equals(".") || e.getName().equals(".."))
                continue;
            for (int idx = 0; idx < tabStop; idx++)
                System.out.print("  ");
            System.out.println("[" + e + "]");
            dumpDirectory(e.getDirectory(), tabStop + 1, new File(curDirectory, e.getName()));
        } else {
            for ( int idx = 0; idx < tabStop; idx++ ) System.out.print("  ");
            System.out.println( e );
            if ( sHasOutputDirectory ) {
                if ( !curDirectory.exists() ) {
                    if ( false == curDirectory.mkdirs() ) {
                        throw new IOException("Unable to create directory: " + curDirectory);                            
                    }
                }
                File curFile = new File(curDirectory, e.getName());
                if ( curFile.exists() ) {
                    throw new IOException("File exists: " + curFile); 
                } else {
                    FsFile f = e.getFile();
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(curFile);
                        FileChannel outputChannel = fos.getChannel();
                        int capacity = sTempBuf.capacity();
                        long length = f.getLength();
                        for ( long pos = 0; pos < length; pos++ ) {
                            int readLength = (int)(length-pos > capacity ? capacity : length-pos);
                            sTempBuf.rewind();
                            sTempBuf.limit(readLength);
                            f.read(pos, sTempBuf);
                            sTempBuf.rewind();
                            while(sTempBuf.remaining() > 0)
                                outputChannel.write(sTempBuf);
                            pos += readLength;
                        }
                    } finally {
                        if ( null != fos ) fos.close();
                    }
                }
            }
        }
    }
}
 
Example 60
Project: eclipselink.runtime   File: EntityMappingsAdvancedJUnitTestCase.java View source code Vote up 5 votes
public void testXMLEntityMappingsWriteOut() {
    try {
        XMLEntityMappings mappings = new XMLEntityMappings();
        mappings.setPersistenceUnitMetadata(new XMLPersistenceUnitMetadata());
        mappings.getPersistenceUnitMetadata().setPersistenceUnitDefaults(new XMLPersistenceUnitDefaults());
        XMLPersistenceUnitMetadata persistenceUnitMetadata = new XMLPersistenceUnitMetadata();
        persistenceUnitMetadata.setPersistenceUnitDefaults(new XMLPersistenceUnitDefaults());
        mappings.setPersistenceUnitMetadata(persistenceUnitMetadata);
        EntityAccessor entity = new EntityAccessor();
        mappings.setEntities(new ArrayList<EntityAccessor>());
        entity.setAttributes(new XMLAttributes());
        entity.getAttributes().setBasicCollections(new ArrayList<BasicCollectionAccessor>());
        entity.getAttributes().getBasicCollections().add(new BasicCollectionAccessor());
        entity.getAttributes().setOneToManys(new ArrayList<OneToManyAccessor>());
        OneToManyAccessor oneToMany = new OneToManyAccessor();
        oneToMany.setCascade(new CascadeMetadata());
        entity.getAttributes().getOneToManys().add(oneToMany);
        entity.getAttributes().setBasics(new ArrayList<BasicAccessor>());
        entity.getAttributes().getBasics().add(new BasicAccessor());

        mappings.getEntities().add(entity);

        XMLEntityMappingsWriter writer = new XMLEntityMappingsWriter();
        FileOutputStream fileOut = new FileOutputStream("XMLWriteOutTest.xml");
        writer.write(mappings, fileOut);
        fileOut.close();

        FileInputStream fileIn = new FileInputStream(fileOut.getFD());
        BufferedReader in = new BufferedReader(new InputStreamReader(fileIn));
        HashSet<String> readStrings = new HashSet<String>();
        while (in.ready()) {
            readStrings.add(in.readLine());
        }
        in.close();

        // Now look for those empty types that we should not see when not explicitly set ...
        assertFalse("Found cascade on delete element", readStrings.contains("<cascade-on-delete"));
        assertFalse("Found non cacheable element", readStrings.contains("<noncacheable"));
        assertFalse("Found private owned element", readStrings.contains("<private-owned"));
        assertFalse("Found xml mapping metadata complete element", readStrings.contains("<xml-mapping-metadata-complete"));
        assertFalse("Found exclude default mappings element", readStrings.contains("<exclude-default-mappings"));
        assertFalse("Found delimeted identifiers element", readStrings.contains("<delimited-identifiers"));
        assertFalse("Found exclude default listeners element", readStrings.contains("<exclude-default-listeners"));
        assertFalse("Found exclude superclass listeners element", readStrings.contains("<exclude-superclass-listeners"));
        assertFalse("Found return update element", readStrings.contains("<return-update"));
        assertFalse("Found cascade all element", readStrings.contains("<cascade-all"));
        assertFalse("Found cascade persist element", readStrings.contains("<cascade-persist"));
        assertFalse("Found cascade merge element", readStrings.contains("<cascade-merge"));
        assertFalse("Found cascade remove element", readStrings.contains("<cascade-remove"));
        assertFalse("Found cascade refresh element", readStrings.contains("<cascade-refresh"));
        assertFalse("Found cascade detach element", readStrings.contains("<cascade-detach"));
    } catch (Exception e) {
        e.printStackTrace();
        fail("An error occurred: " + e.getMessage());
    }
}