Java Code Examples for java.io.FileOutputStream#write()

The following examples show how to use java.io.FileOutputStream#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AttachmentStore.java    From NIM_Android_UIKit with MIT License 6 votes vote down vote up
/**
 * 把数据保存到文件系统中,并且返回其大小
 *
 * @param data
 * @param filePath
 * @return 如果保存失败, 则返回-1
 */
public static long save(byte[] data, String filePath) {
    if (TextUtils.isEmpty(filePath)) {
        return -1;
    }

    File f = new File(filePath);
    if (f.getParentFile() == null) {
        return -1;
    }

    if (!f.getParentFile().exists()) {// 如果不存在上级文件夹
        f.getParentFile().mkdirs();
    }
    try {
        f.createNewFile();
        FileOutputStream fout = new FileOutputStream(f);
        fout.write(data);
        fout.close();
    } catch (IOException e) {
        e.printStackTrace();
        return -1;
    }
    return f.length();
}
 
Example 2
Source File: GetRoot.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
static void setUp() throws Exception {
    testarray = new float[1024];
    for (int i = 0; i < 1024; i++) {
        double ii = i / 1024.0;
        ii = ii * ii;
        testarray[i] = (float)Math.sin(10*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(1.731 + 2*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(0.231 + 6.3*ii*2*Math.PI);
        testarray[i] *= 0.3;
    }
    test_byte_array = new byte[testarray.length*2];
    AudioFloatConverter.getConverter(format).toByteArray(testarray, test_byte_array);
    test_file = File.createTempFile("test", ".raw");
    FileOutputStream fos = new FileOutputStream(test_file);
    fos.write(test_byte_array);
}
 
Example 3
Source File: LoginBean.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public String getAvatarImage(AvatarImage avatar) {
	if (avatar != null) {
		String fileName = "avatars/" + "a" + avatar.getId() + ".jpg";
		String path = LoginBean.outputFilePath + "/" + fileName;
		byte[] image = avatar.getImage();
		if (image != null) {
			File file = new File(path);
			if (!file.exists()) {
				try {
					FileOutputStream stream = new FileOutputStream(file);
					stream.write(image);
					stream.flush();
					stream.close();
				} catch (IOException exception) {
					error(exception);
					return "images/bot.png";
				}
			}
			return fileName;
		}
	}
	return "images/bot.png";
}
 
Example 4
Source File: GetRoot.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
static void setUp() throws Exception {
    testarray = new float[1024];
    for (int i = 0; i < 1024; i++) {
        double ii = i / 1024.0;
        ii = ii * ii;
        testarray[i] = (float)Math.sin(10*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(1.731 + 2*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(0.231 + 6.3*ii*2*Math.PI);
        testarray[i] *= 0.3;
    }
    test_byte_array = new byte[testarray.length*2];
    AudioFloatConverter.getConverter(format).toByteArray(testarray, test_byte_array);
    test_file = File.createTempFile("test", ".raw");
    FileOutputStream fos = new FileOutputStream(test_file);
    fos.write(test_byte_array);
}
 
Example 5
Source File: MultiFilesOper.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 创建临时文件,里面保存合并打开的文件路径
 * @param selectIFiles
 * @throws Exception
 */
private File createTempFile() throws Exception {
	String tempFile = selectedProject.getLocation().append(_TEMPFOLDER).append(System.currentTimeMillis() + _XLP).toOSString();
	FileOutputStream output = new FileOutputStream(tempFile);
	StringBuffer dataSB = new StringBuffer();
	dataSB.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
	dataSB.append("<mergerFiles>\n");
	for (IFile iFile : selectIFiles) {
		dataSB.append(MessageFormat.format("\t<mergerFile filePath=\"{0}\"/>\n", TextUtil.cleanSpecialString(iFile.getLocation().toOSString())));
	}
	dataSB.append("</mergerFiles>\n");
	output.write(dataSB.toString().getBytes("UTF-8"));
	output.close();
	File file = new File(tempFile);
	return file;
}
 
Example 6
Source File: ResourceUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取 Assets 资源文件数据并保存到本地
 * @param fileName 文件名
 * @param file     文件保存地址
 * @return {@code true} success, {@code false} fail
 */
public static boolean saveAssetsFormFile(final String fileName, final File file) {
    try {
        // 获取 Assets 文件
        InputStream is = open(fileName);
        // 存入 SDCard
        FileOutputStream fos = new FileOutputStream(file);
        // 设置数据缓冲
        byte[] buffer = new byte[1024];
        // 创建输入输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        // 保存数据
        byte[] bytes = baos.toByteArray();
        // 写入保存的文件
        fos.write(bytes);
        // 关闭流
        CloseUtils.closeIOQuietly(baos, is);
        fos.flush();
        CloseUtils.closeIOQuietly(fos);
        return true;
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "saveAssetsFormFile");
    }
    return false;
}
 
Example 7
Source File: AdbCrypto.java    From AppOpsX with MIT License 5 votes vote down vote up
/**
 * Saves the AdbCrypto's key pair to the specified files.
 * @param privateKey The file to store the encoded private key
 * @param publicKey The file to store the encoded public key
 * @throws IOException If the files cannot be written
 */
public void saveAdbKeyPair(File privateKey, File publicKey) throws IOException
{		
	FileOutputStream privOut = new FileOutputStream(privateKey);
	FileOutputStream pubOut = new FileOutputStream(publicKey);
	
	privOut.write(keyPair.getPrivate().getEncoded());
	pubOut.write(keyPair.getPublic().getEncoded());
	
	privOut.close();
	pubOut.close();
}
 
Example 8
Source File: BaseCache.java    From mvp-android with MIT License 5 votes vote down vote up
private void saveCacheFile(String fileContent) {
    try {
        FileOutputStream stream = new FileOutputStream(cacheFile);
        stream.write(fileContent.getBytes());
        stream.close();
    } catch (IOException e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
}
 
Example 9
Source File: UndeployTaskTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test
public void testCelosCiUndeployContext() throws Exception {


    String hadoopCoreUrl = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/core-site.xml").getFile();
    String hadoopHdfsUrl = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/ci/testing/config/hdfs-site.xml").getFile();

    String targetFileStr = "{\n" +
            "    \"security.settings\": \"secsettings\",\n" +
            "    \"workflows.dir.uri\": \"celoswfdir\",\n" +
            "    \"hadoop.hdfs-site.xml\": \"" + hadoopHdfsUrl +"\",\n" +
            "    \"hadoop.core-site.xml\": \"" + hadoopCoreUrl +"\",\n" +
            "    \"defaults.dir.uri\": \"defdir\"\n" +
            "}\n";

    File targetFile = tempDir.newFile();
    FileOutputStream stream = new FileOutputStream(targetFile);
    stream.write(targetFileStr.getBytes());
    stream.flush();

    CiCommandLine commandLine = new CiCommandLine(targetFile.toURI().toString(), "UNDEPLOY", "deploydir", "workflow", "testDir", "uname", false, null, "/hdfsRoot");
    UndeployTask celosCiDeploy = new UndeployTask(commandLine);

    CelosCiContext context = celosCiDeploy.getCiContext();

    Assert.assertEquals(context.getDeployDir(), commandLine.getDeployDir());
    Assert.assertEquals(context.getHdfsPrefix(), "");
    Assert.assertEquals(context.getMode(), commandLine.getMode());
    Assert.assertEquals(context.getTarget().getWorkflowsDirUri(), URI.create("celoswfdir"));
    Assert.assertEquals(context.getTarget().getDefaultsDirUri(), URI.create("defdir"));
    Assert.assertEquals(context.getTarget().getPathToCoreSite(), URI.create(hadoopCoreUrl));
    Assert.assertEquals(context.getTarget().getPathToHdfsSite(), URI.create(hadoopHdfsUrl));
    Assert.assertEquals(context.getUserName(), commandLine.getUserName());
    Assert.assertEquals(context.getWorkflowName(), commandLine.getWorkflowName());
}
 
Example 10
Source File: SelfSampleVFSTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void write(File f, String content) throws IOException {
    FileOutputStream os = new FileOutputStream(f);
    try {
        os.write(content.getBytes());
    } finally {
        os.close();
    }
}
 
Example 11
Source File: DirProviderTest.java    From cwac-provider with Apache License 2.0 5 votes vote down vote up
static private void copy(InputStream in, File dst) throws IOException {
  FileOutputStream out=new FileOutputStream(dst);
  byte[] buf=new byte[1024];
  int len;

  while ((len=in.read(buf)) > 0) {
    out.write(buf, 0, len);
  }

  in.close();
  out.close();
}
 
Example 12
Source File: AAH_DownloadService.java    From AutoplayVideos with Apache License 2.0 5 votes vote down vote up
private boolean downloadData(String requestUrl,String path) {
    try {
        File rootDir = new File(path);
        if (!rootDir.exists()) {
            rootDir.mkdir();
        }

        File rootFile = new File(rootDir, new Date().getTime() + ".mp4");
        if (!rootFile.exists()) {
            rootFile.createNewFile();
        }

        URL url = new URL(requestUrl);
        HttpURLConnection c = (HttpURLConnection) url.openConnection();
        c.setRequestMethod("GET");
        c.connect();
        FileOutputStream f = new FileOutputStream(rootFile);
        InputStream in = c.getInputStream();
        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();
        AAH_Utils.saveString(getApplicationContext(), requestUrl, rootFile.getAbsolutePath());
        return true;
    } catch (Exception e) {
        return false;
    }

}
 
Example 13
Source File: DocumentArchive.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a DocumentsArchive instance for opening, browsing and accessing
 * documents within the archive passed as a file descriptor.
 *
 * <p>Note, that this method should be used only if the document does not exist
 * on the local storage. A snapshot file will be created, which may be slower
 * and consume significant resources, in contrast to using
 * {@see createForLocalFile(Context, File, String, char, Uri}.
 *
 * @param context Context of the provider.
 * @param descriptor File descriptor for the archive's contents.
 * @param documentId ID of the archive document.
 * @param idDelimiter Delimiter for constructing IDs of documents within the archive.
 *            The delimiter must never be used for IDs of other documents.
 * @param Uri notificationUri Uri for notifying that the archive file has changed.
 * @see createForLocalFile(Context, File, String, char, Uri)
 */
public static DocumentArchive createForParcelFileDescriptor(
        Context context, ParcelFileDescriptor descriptor, String documentId,
        char idDelimiter, @Nullable Uri notificationUri)
        throws IOException {
    File snapshotFile = null;
    try {
        // Create a copy of the archive, as ZipFile doesn't operate on streams.
        // Moreover, ZipInputStream would be inefficient for large files on
        // pipes.
        snapshotFile = File.createTempFile("android.support.provider.snapshot{",
                "}.zip", context.getCacheDir());

        try {
            final FileOutputStream outputStream =
                    new ParcelFileDescriptor.AutoCloseOutputStream(
                            ParcelFileDescriptor.open(
                                    snapshotFile, ParcelFileDescriptor.MODE_WRITE_ONLY));
            final ParcelFileDescriptor.AutoCloseInputStream inputStream =
                    new ParcelFileDescriptor.AutoCloseInputStream(descriptor);
            final byte[] buffer = new byte[32 * 1024];
            int bytes;
            while ((bytes = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytes);
            }
            outputStream.flush();
            return new DocumentArchive(context, snapshotFile, documentId, idDelimiter,
                    notificationUri);
        } catch (Exception e){
            CrashReportingManager.logException(e);
            return null;
        }
    } finally {
        // On UNIX the file will be still available for processes which opened it, even
        // after deleting it. Remove it ASAP, as it won't be used by anyone else.
        if (snapshotFile != null) {
            snapshotFile.delete();
        }
    }
}
 
Example 14
Source File: FileServiceDataSetCRUD.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Decompress downloaded file
 *
 * @param response
 * @return
 * @throws IOException
 */

File decompressByteArray(byte[] response) throws IOException {
	logger.debug("IN");
	// write byteArray
	File dir = new File(System.getProperty("java.io.tmpdir"));
	Random generator = new Random();
	int randomInt = generator.nextInt();
	String fileName = Integer.valueOf(randomInt).toString();
	File zipFile = File.createTempFile(fileName, ".zip", dir);

	logger.debug("created temporary zip file " + zipFile.getAbsolutePath());

	FileOutputStream fos = new FileOutputStream(zipFile);
	fos.write(response);
	fos.close();

	// create folder to store temporary files
	File temp = new File(System.getProperty("java.io.tmpdir") + "/" + fileName);
	temp.mkdir();

	logger.debug("Unzip file in  " + temp.getAbsolutePath());

	new SpagoBIAccessUtils().unzip(zipFile, temp);
	logger.debug("OUT");
	return temp;
}
 
Example 15
Source File: MLet.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Search the specified native library in any of the JAR files
 * loaded by this classloader.  If the library is found copy it
 * into the library directory and return the absolute path.  If
 * the library is not found then return null.
 */
private synchronized String loadLibraryAsResource(String libname) {
    try {
        InputStream is = getResourceAsStream(
                libname.replace(File.separatorChar,'/'));
        if (is != null) {
            try {
                File directory = new File(libraryDirectory);
                directory.mkdirs();
                File file = Files.createTempFile(directory.toPath(),
                                                 libname + ".", null)
                                 .toFile();
                file.deleteOnExit();
                FileOutputStream fileOutput = new FileOutputStream(file);
                try {
                    byte[] buf = new byte[4096];
                    int n;
                    while ((n = is.read(buf)) >= 0) {
                       fileOutput.write(buf, 0, n);
                    }
                } finally {
                    fileOutput.close();
                }
                if (file.exists()) {
                    return file.getAbsolutePath();
                }
            } finally {
                is.close();
            }
        }
    } catch (Exception e) {
        MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(),
                "loadLibraryAsResource",
                "Failed to load library : " + libname, e);
        return null;
    }
    return null;
}
 
Example 16
Source File: CpuMetricsCollectorTest.java    From Battery-Metrics with MIT License 4 votes vote down vote up
private static String overwriteFile(File file, String contents) throws IOException {
  FileOutputStream os = new FileOutputStream(file, false);
  os.write(contents.getBytes());
  os.close();
  return file.getCanonicalPath();
}
 
Example 17
Source File: S4U2selfAsServerGSS.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Oid mech;
    if (args[0].equals("spnego")) {
        mech = GSSUtil.GSS_SPNEGO_MECH_OID;
    } else if (args[0].contains("krb5")) {
        mech = GSSUtil.GSS_KRB5_MECH_OID;
    } else {
        throw new Exception("Unknown mech");
    }

    OneKDC kdc = new OneKDC(null);
    kdc.writeJAASConf();
    kdc.setOption(KDC.Option.PREAUTH_REQUIRED, false);
    Map<String,List<String>> map = new HashMap<>();
    map.put(OneKDC.SERVER + "@" + OneKDC.REALM, Arrays.asList(
            new String[]{OneKDC.SERVER + "@" + OneKDC.REALM}));
    kdc.setOption(KDC.Option.ALLOW_S4U2PROXY, map);
    kdc.setOption(KDC.Option.ALLOW_S4U2SELF, Arrays.asList(
            new String[]{OneKDC.SERVER + "@" + OneKDC.REALM}));

    Context s, b;
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    System.setProperty("java.security.auth.login.config", OneKDC.JAAS_CONF);
    File f = new File(OneKDC.JAAS_CONF);
    FileOutputStream fos = new FileOutputStream(f);
    fos.write((
            "com.sun.security.jgss.krb5.accept {\n" +
            "    com.sun.security.auth.module.Krb5LoginModule required\n" +
            "    principal=\"" + OneKDC.SERVER + "\"\n" +
            "    useKeyTab=true\n" +
            "    storeKey=true;\n};\n"
            ).getBytes());
    fos.close();
    Security.setProperty("auth.login.defaultCallbackHandler", "OneKDC$CallbackForClient");
    s = Context.fromThinAir();
    b = Context.fromThinAir();
    s.startAsServer(mech);

    Context p = s.impersonate(OneKDC.USER);

    p.startAsClient(OneKDC.SERVER, mech);
    b.startAsServer(mech);
    Context.handshake(p, b);

    String n1 = p.x().getSrcName().toString().split("@")[0];
    String n2 = b.x().getSrcName().toString().split("@")[0];
    if (!n1.equals(OneKDC.USER) || !n2.equals(OneKDC.USER)) {
        throw new Exception("Delegation failed");
    }
}
 
Example 18
Source File: LocalFilesystem.java    From keemob with MIT License 4 votes vote down vote up
@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
		int offset, boolean isBinary) throws IOException, NoModificationAllowedException {

       boolean append = false;
       if (offset > 0) {
           this.truncateFileAtURL(inputURL, offset);
           append = true;
       }

       byte[] rawData;
       if (isBinary) {
           rawData = Base64.decode(data, Base64.DEFAULT);
       } else {
           rawData = data.getBytes(Charset.defaultCharset());
       }
       ByteArrayInputStream in = new ByteArrayInputStream(rawData);
       try
       {
       	byte buff[] = new byte[rawData.length];
           String absolutePath = filesystemPathForURL(inputURL);
           FileOutputStream out = new FileOutputStream(absolutePath, append);
           try {
           	in.read(buff, 0, buff.length);
           	out.write(buff, 0, rawData.length);
           	out.flush();
           } finally {
           	// Always close the output
           	out.close();
           }
           if (isPublicDirectory(absolutePath)) {
               broadcastNewFile(Uri.fromFile(new File(absolutePath)));
           }
       }
       catch (NullPointerException e)
       {
           // This is a bug in the Android implementation of the Java Stack
           NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
           realException.initCause(e);
           throw realException;
       }

       return rawData.length;
}
 
Example 19
Source File: TestWinUtils.java    From hadoop with Apache License 2.0 4 votes vote down vote up
private void writeFile(File file, String content) throws IOException {
  byte[] data = content.getBytes();
  FileOutputStream os = new FileOutputStream(file);
  os.write(data);
  os.close();
}
 
Example 20
Source File: CompressionUtilities.java    From geopaparazzi with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Uncompress a compressed file to the contained structure.
 *
 * @param zipFile      the zip file that needs to be unzipped
 * @param destFolder   the folder into which unzip the zip file and create the folder structure
 * @param addTimeStamp if <code>true</code>, the timestamp is added if the base folder already exists.
 * @return the name of the internal base folder or <code>null</code>.
 * @throws IOException if something goes wrong.
 */
public static String unzipFolder(String zipFile, String destFolder, boolean addTimeStamp) throws IOException {
    SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyyMMddHHmmss"); //$NON-NLS-1$

    ZipFile zf = new ZipFile(zipFile);
    Enumeration<? extends ZipEntry> zipEnum = zf.entries();

    String firstName = null;
    String newFirstName = null;

    while (zipEnum.hasMoreElements()) {
        ZipEntry item = (ZipEntry) zipEnum.nextElement();

        String itemName = item.getName();
        if (firstName == null) {
            int firstSlash = itemName.indexOf('/');
            if (firstSlash != -1) {
                firstName = itemName.substring(0, firstSlash);
                newFirstName = firstName;
                File baseFile = new File(destFolder + File.separator + firstName);
                if (baseFile.exists()) {
                    if (addTimeStamp) {
                        newFirstName = firstName + "_" + dateTimeFormatter.format(new Date()); //$NON-NLS-1$
                    } else {
                        throw new IOException(FILE_EXISTS + baseFile); //$NON-NLS-1$
                    }
                }
            }
        }
        itemName = itemName.replaceFirst(firstName, newFirstName);

        if (item.isDirectory()) {
            File newdir = new File(destFolder + File.separator + itemName);
            if (!newdir.mkdir())
                throw new IOException();
        } else {
            String newfilePath = destFolder + File.separator + itemName;
            File newFile = new File(newfilePath);
            File parentFile = newFile.getParentFile();
            if (!parentFile.exists()) {
                if (!parentFile.mkdirs())
                    throw new IOException();
            }
            InputStream is = zf.getInputStream(item);
            FileOutputStream fos = new FileOutputStream(newfilePath);
            byte[] buffer = new byte[512];
            int readchars = 0;
            while ((readchars = is.read(buffer)) != -1) {
                fos.write(buffer, 0, readchars);
            }
            is.close();
            fos.close();
        }
    }
    zf.close();

    return newFirstName;
}