Java Code Examples for java.io.FileOutputStream.flush()

The following are Jave code examples for showing how to use flush() of the java.io.FileOutputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: excel-utils   File: TestUser.java   View Source Code Vote up 8 votes
@Test
public void testExcel07() throws IOException{
	List<UserPlus> list = getData(0, 20000);
	Map<String, String> map = new HashMap<String,String>();
	map.put("msg", "用户信息导出报表");
	map.put("status", "导出成功");
	long start = System.currentTimeMillis();
	Workbook workbook = ExcelExportUtil.exportExcel07(UserPlus.class, list, map, true);
	long end = System.currentTimeMillis();
	System.out.println("耗时:" + (end - start ) + "毫秒");
	FileOutputStream outputStream = new FileOutputStream("D:/test/user.xlsx");
	workbook.write(outputStream);
	if(SXSSFWorkbook.class.equals(workbook.getClass())){
		SXSSFWorkbook wb = (SXSSFWorkbook)workbook;
		wb.dispose();
	}
	outputStream.flush();
	outputStream.close();
}
 
Example 2
Project: pc-android-controller-android   File: ImageCompressUtil.java   View Source Code Vote up 6 votes
/**
         * @param b Bitmap
         * @return 图片存储的位置
         */
        public static File saveImg(Bitmap b, String name) throws Exception {
            String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "test/headImg/";
            File mediaFile = new File(path + File.separator + name + ".jpg");
            if (mediaFile.exists()) {
                mediaFile.delete();

            }
            if (!new File(path).exists()) {
                new File(path).mkdirs();
            }
            mediaFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(mediaFile);
            b.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            b.recycle();
            b = null;
            System.gc();
//            return mediaFile.getPath();
            return mediaFile;
        }
 
Example 3
Project: spring-i18n-support   File: ExcelWriterTest.java   View Source Code Vote up 6 votes
@Test
public void testWriteSimpleUnknown() throws Exception
{
	FileOutputStream fout = null;
	try
	{
		String dir = this.getClass().getResource("/").getFile();
		List<MessageResourceEntry> messages = messages();
		this.writer.createExcel(messages, new File(dir + "test-out-f.xlsx"), "abc");
	}
	finally
	{
		if (fout != null)
		{
			try
			{
				fout.flush();
				fout.close();
			}
			finally
			{
				fout = null;
			}
		}
	}
}
 
Example 4
Project: GitHub   File: FileAsyncHttpResponseHandler.java   View Source Code Vote up 6 votes
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        long contentLength = entity.getContentLength();
        FileOutputStream buffer = new FileOutputStream(getTargetFile(), this.append);
        if (instream != null) {
            try {
                byte[] tmp = new byte[BUFFER_SIZE];
                int l, count = 0;
                // do not send messages if request has been cancelled
                while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                    count += l;
                    buffer.write(tmp, 0, l);
                    sendProgressMessage(count, contentLength);
                }
            } finally {
                AsyncHttpClient.silentCloseInputStream(instream);
                buffer.flush();
                AsyncHttpClient.silentCloseOutputStream(buffer);
            }
        }
    }
    return null;
}
 
Example 5
Project: GitHub   File: RangeFileAsyncHttpResponseHandler.java   View Source Code Vote up 6 votes
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        long contentLength = entity.getContentLength() + current;
        FileOutputStream buffer = new FileOutputStream(getTargetFile(), append);
        if (instream != null) {
            try {
                byte[] tmp = new byte[BUFFER_SIZE];
                int l;
                while (current < contentLength && (l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                    current += l;
                    buffer.write(tmp, 0, l);
                    sendProgressMessage(current, contentLength);
                }
            } finally {
                instream.close();
                buffer.flush();
                buffer.close();
            }
        }
    }
    return null;
}
 
Example 6
Project: excel-utils   File: TestUser.java   View Source Code Vote up 6 votes
/**
 * 分批写出20w条数据
 * 
 * @throws IOException 
 */
@Test
public void batchesExport() throws IOException {
	Map<String, String> map = new HashMap<String,String>();
	map.put("msg", "用户信息导出报表");
	map.put("status", "导出成功");
	
	Workbook workbook = null;
	//分两次写入20w条数据
	List<UserPlus> list;
	for(int i = 0 ; i < 2 ; i++){
		list = getData(i*100000, 100000);
		workbook = ExcelExportUtil.exportExcel03(UserPlus.class, list, map,workbook);
		
	}
	FileOutputStream outputStream = new FileOutputStream("D:/test/user1.xls");
	workbook.write(outputStream);
	outputStream.flush();
	outputStream.close();
}
 
Example 7
Project: godlibrary   File: FileUtils.java   View Source Code Vote up 6 votes
/**
 * 保存Image的方法,有sd卡存储到sd卡,没有就存储到手机目录
 *
 * @param fileName
 * @param bitmap
 */
public File saveBitmap(String dirsName, String fileName, Bitmap bitmap) {
    if (bitmap == null) {
        return null;
    }
    try {
        File file = createSDFile(dirsName, fileName);
        FileOutputStream fos = new FileOutputStream(file);
        String Type = fileName.substring(fileName.lastIndexOf(".") + 1)
                .toUpperCase();
        if ("PNG".equals(Type) || "png".equals(Type)) {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } else {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
        }

        fos.flush();
        fos.close();
        scannerFile(file.getPath());
        return file;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 8
Project: AndroidAsyncHTTP   File: RangeFileAsyncHttpResponseHandler.java   View Source Code Vote up 6 votes
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        long contentLength = entity.getContentLength() + current;
        FileOutputStream buffer = new FileOutputStream(getTargetFile(), append);
        if (instream != null) {
            try {
                byte[] tmp = new byte[BUFFER_SIZE];
                int l;
                while (current < contentLength && (l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                    current += l;
                    buffer.write(tmp, 0, l);
                    sendProgressMessage(current, contentLength);
                }
            } finally {
                instream.close();
                buffer.flush();
                buffer.close();
            }
        }
    }
    return null;
}
 
Example 9
Project: android-project-gallery   File: RangeFileAsyncHttpResponseHandler.java   View Source Code Vote up 6 votes
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        long contentLength = entity.getContentLength() + current;
        FileOutputStream buffer = new FileOutputStream(getTargetFile(), append);
        if (instream != null) {
            try {
                byte[] tmp = new byte[BUFFER_SIZE];
                int l;
                while (current < contentLength && (l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                    current += l;
                    buffer.write(tmp, 0, l);
                    sendProgressMessage((int) current, (int) contentLength);
                }
            } finally {
                instream.close();
                buffer.flush();
                buffer.close();
            }
        }
    }
    return null;
}
 
Example 10
Project: LifeHelper   File: UserActivity.java   View Source Code Vote up 6 votes
public static String saveBitmap(Bitmap bitmap, Bitmap.CompressFormat format,
                                int quality, File destFile) {
    try {
        FileOutputStream fos = new FileOutputStream(destFile);
        if (bitmap.compress(format, quality, fos)) {
            fos.flush();
            fos.close();
        }
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
        return destFile.getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 11
Project: ImageClassify   File: UnZipMainThread.java   View Source Code Vote up 5 votes
@Override
public void run() {
    super.run();
    try {
        listener.zipStart();
        long sumLength = 0;
        // 获取解压之后文件的大小,用来计算解压的进度
        long ziplength = getZipTrueSize(zipFileString);
        FileInputStream inputStream = new FileInputStream(zipFileString);
        ZipInputStream inZip = new ZipInputStream(inputStream);
        ZipEntry zipEntry;
        String szName = "";
        while ((zipEntry = inZip.getNextEntry()) != null) {
            szName = zipEntry.getName();
            if (zipEntry.isDirectory()) {
                szName = szName.substring(0, szName.length() - 1);
                File folder = new File(outPathString + File.separator + szName);
                folder.mkdirs();
            } else {
                File file = new File(outPathString + File.separator + szName);
                file.createNewFile();
                FileOutputStream out = new FileOutputStream(file);
                int len;
                byte[] buffer = new byte[1024];
                while ((len = inZip.read(buffer)) != -1) {
                    sumLength += len;
                    int progress = (int) ((sumLength * 100) / ziplength);
                    updateProgress(progress, listener);
                    out.write(buffer, 0, len);
                    out.flush();
                }
                out.close();
            }
        }
        listener.zipSuccess();
        inZip.close();
    } catch (Exception e) {
        listener.zipFail();
    }
}
 
Example 12
Project: anitrend-app   File: Cache.java   View Source Code Vote up 5 votes
private boolean fileCreator(Token ref) throws IOException{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(ref);
    oos.flush();
    oos.close();
    if(mFile.canWrite()) {
        FileOutputStream fos = new FileOutputStream(mFile,false);
        fos.write(bos.toByteArray());
        fos.flush();
        fos.close();
        return true;
    }
    return false;
}
 
Example 13
Project: rtmp-rtsp-stream-client-java   File: YUVUtil.java   View Source Code Vote up 5 votes
public void dumpYUVData(byte[] buffer, int len, String name) {
  File f = new File(Environment.getExternalStorageDirectory().getPath() + "/tmp/", name);
  if (f.exists()) {
    f.delete();
  }
  try {
    FileOutputStream out = new FileOutputStream(f);
    out.write(buffer);
    out.flush();
    out.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 14
Project: quicknotes   File: QuickNotesManager.java   View Source Code Vote up 5 votes
/**
 * Save the settings to ideaquicknotes.xml
 */
public static boolean saveSettings(Element element) {
    // Get an instane of XMLOutputter
    XMLOutputter outputter = new XMLOutputter();
    File settingsFile = getSettingsFile();
    if (settingsFile != null) {
        try {
            QuickNotesManager mgr = QuickNotesManager.getInstance();
            element.setAttribute("showlinenumbers", mgr.isShowLineNumbers() ? "Y" : "N");
            element.setAttribute("toolbarlocation", String.valueOf(mgr.getToolbarLocation()));
            element.setAttribute("wordwrap", mgr.isWordWrap() ? "Y" : "N");
            element.setAttribute("filelocation", mgr.getFileLocation_default());

            Font font = mgr.getNotesFont();
            element.setAttribute("fontname", font.getFontName());
            element.setAttribute("fontsize", String.valueOf(font.getSize()));

            Color fontColor = mgr.getFontColor();
            element.setAttribute("fontColorDefault", mgr.fontColor_default ? "Y" : "N");
            element.setAttribute("fontColorRed", String.valueOf(fontColor.getRed()));
            element.setAttribute("fontColorGreen", String.valueOf(fontColor.getGreen()));
            element.setAttribute("fontColorBlue", String.valueOf(fontColor.getBlue()));

            Color bgColor = mgr.getBackgroundColor();
            element.setAttribute("bgColorDefault", mgr.isBackgroundColor_default() ? "Y" : "N");
            element.setAttribute("bgColorRed", String.valueOf(bgColor.getRed()));
            element.setAttribute("bgColorGreen", String.valueOf(bgColor.getGreen()));
            element.setAttribute("bgColorBlue", String.valueOf(bgColor.getBlue()));

            Color bgLineColor = mgr.getBackgroundLineColor();
            element.setAttribute("bgLineColorShow", mgr.isShowBackgroundLines() ? "Y" : "N");
            element.setAttribute("bgLineColorDefault", mgr.isBackgroundLineColor_default() ? "Y" : "N");
            element.setAttribute("bgLineColorRed", String.valueOf(bgLineColor.getRed()));
            element.setAttribute("bgLineColorGreen", String.valueOf(bgLineColor.getGreen()));
            element.setAttribute("bgLineColorBlue", String.valueOf(bgLineColor.getBlue()));

            Color lineNumberColor = mgr.getLineNumberColor();
            element.setAttribute("lineNumberColorDefault", mgr.isLineNumberColor_default() ? "Y" : "N");
            element.setAttribute("lineNumberColorRed", String.valueOf(lineNumberColor.getRed()));
            element.setAttribute("lineNumberColorGreen", String.valueOf(lineNumberColor.getGreen()));
            element.setAttribute("lineNumberColorBlue", String.valueOf(lineNumberColor.getBlue()));

            FileOutputStream fos = new FileOutputStream(settingsFile);
            outputter.setFormat(Format.getPrettyFormat()); // make it Pretty!!!
            outputter.output(element, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            return false;
        }
    }
    return true;
}
 
Example 15
Project: Watermark   File: CropPresenter.java   View Source Code Vote up 5 votes
public void saveImage(Bitmap cropBitmap) {
    try {
        FileOutputStream fos = new FileOutputStream(mCroppedFile);
        cropBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example 16
Project: Ocr-android   File: SplashActivity.java   View Source Code Vote up 5 votes
private void copy(String src, String dest) throws IOException {
    String[] fileNames = context.getAssets().list(src);
    if (fileNames.length > 0) {
        File file = new File(dest);
        if (!file.exists()) {
            file.mkdirs();
        }
        for (String fileName : fileNames) {
            // assets 文件夹下的目录
            if (!TextUtils.isEmpty(src)) {
                copy(src + File.separator + fileName, dest + File.separator + fileName);
            } else { // assets 文件夹
                copy(fileName, dest + File.separator + fileName);
            }
        }
    } else {
        publishProgress(getString(R.string.string_splash_copy) + src + " ...");
        File outFile = new File(dest);
        InputStream is = context.getAssets().open(src);
        FileOutputStream fos = new FileOutputStream(outFile);
        byte[] buffer = new byte[1024];
        int byteCount;
        while ((byteCount = is.read(buffer)) != -1) {
            fos.write(buffer, 0, byteCount);
        }
        fos.flush();
        is.close();
        fos.close();
    }
}
 
Example 17
Project: sctalk   File: FileUtil.java   View Source Code Vote up 5 votes
public static String saveAudioResourceToFile(byte[] content,long userId) {
    try {
        String audioSavePath = CommonUtil.getAudioSavePath(userId);
        File file = new File(audioSavePath);
        FileOutputStream fops = new FileOutputStream(file);
        fops.write(content);
        fops.flush();
        fops.close();
        return audioSavePath;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 18
Project: unitimes   File: CurModel.java   View Source Code Vote up 4 votes
public static void main(String[] args) {
 	try {
 		Logger.getRootLogger().setLevel(Level.DEBUG);
 		
 		List<CurStudent> students = new ArrayList<CurStudent>();
 		for (int i = 0; i < 20; i++)
 			students.add(new CurStudent(new Long(1 + i), (i < 10 ? 0.5f: 2f)));
 		CurModel m = new CurModel(students);
 		for (int i = 1; i <= 10; i++)
 			m.addCourse((long)i, "C" + i,  2 * i, null);
 		for (int i = 1; i < 10; i++)
 			for (int j = i + 1; j <= 10; j++)
 				m.setTargetShare((long)i, (long)j, i, false);
 		m.setStudentLimits();
 		
Document d0 = DocumentHelper.createDocument();
Assignment<CurVariable, CurValue> a = new DefaultSingleAssignment<CurVariable, CurValue>();
m.saveAsXml(d0.addElement("curriculum"), a);
sLog.info(d0.asXML());

 		sLog.info("Loaded: " + ToolBox.dict2string(m.getInfo(a), 2));

 		m.solve(a);

 		sLog.info("Solution: " + ToolBox.dict2string(m.getInfo(a), 2));
 		
Document d1 = DocumentHelper.createDocument();
m.saveAsXml(d1.addElement("curriculum"), a);
sLog.info(d1.asXML());

Solution<CurVariable, CurValue> x = loadFromXml(d1.getRootElement());
sLog.info("Reloaded: " + ToolBox.dict2string(x.getInfo(), 2));
         
 		TreeSet<CurCourse> courses = new TreeSet<CurCourse>(new Comparator<CurCourse>() {
 			public int compare(CurCourse c1, CurCourse c2) {
 				int cmp = c1.getCourseName().compareTo(c2.getCourseName());
 				if (cmp != 0) return cmp;
 				return c1.getCourseId().compareTo(c2.getCourseId());
 			}
 		});
 		courses.addAll(m.getCourses());
         int penalty = 0;
 		for (CurCourse course: courses) {
 			sLog.info(course.getCourseName() + ": " + m.getCourse(course.getCourseId()).getStudents(a) + " (" + course.getSize(a) + "/" + course.getOriginalMaxSize() + ")");
     		for (CurCourse other: courses) {
     			if (other.getCourseId() <= course.getCourseId()) continue;
 				double share = course.share(a, other);
 				double target = course.getTargetShare(other.getCourseId());
 				sLog.info("  " + other.getCourseName() + ": share=" + share + ", target=" + target + ", penalty=" + Math.abs(target - share)); 
 				penalty += Math.abs(target - share);
 			}
 		}
 		sLog.info("Total penalty: " + penalty);
 		
Document doc = DocumentHelper.createDocument();
m.saveAsXml(doc.addElement("curriculum"), a);
FileOutputStream fos = new FileOutputStream("/Users/muller/solution.xml");
         (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(doc);
         fos.flush();
         fos.close();

 	} catch (Exception e) {
 		e.printStackTrace();
 	}
 }
 
Example 19
Project: Raffler-Android   File: ChatActivity.java   View Source Code Vote up 4 votes
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    switch(requestCode) {
        case PICK_IMAGE_ID:
            if(resultCode != RESULT_CANCELED){
                /*if (data != null) {
                    if (data.getExtras() == null){
                        Bitmap bitmap = ImagePicker.getImageFromResult(this, resultCode, data);
                        Log.e("FROM GALLERY OR PHOTOS", bitmap.toString());
                    }else{
                        Bitmap photo = (Bitmap) data.getExtras().get("data");
                        Log.e("FROM CAMERA", data.getExtras().toString());
                    }
                }*/
                try{
                    Bitmap bitmap = ImagePicker.getImageFromResult(this, resultCode, data);
                    //create a file to write bitmap data
                    File f = new File(this.getCacheDir(), "tmp.jpg");
                    f.createNewFile();

                    //Convert bitmap to byte array
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                    byte[] bitmapdata = bos.toByteArray();

                    //write the bytes in file
                    FileOutputStream fos = new FileOutputStream(f);
                    fos.write(bitmapdata);
                    fos.flush();
                    fos.close();

                    Uri uri = Uri.fromFile(f);
                    sendPhoto(uri);

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            break;
        case REQUEST_GALLERY:
            if (resultCode != RESULT_CANCELED) {
                if (data != null) {
                    mCurrentPhotoPath = data.getData();
                    if (mCurrentPhotoPath != null) {
                        sendPhoto(mCurrentPhotoPath);
                    }
                }
            }
            break;
        case REQUEST_CAMERA:
            if (resultCode != RESULT_CANCELED) {
                if (mCurrentPhotoPath != null) {
                    sendPhoto(mCurrentPhotoPath);
                }
            }
            break;
        case REQUEST_CONTACT:
            if (resultCode == RESULT_OK) {
                // Get the URI and query the content provider for the phone number
                Uri contactUri = data.getData();

                /* This method was removed at git version (v1.0.2 b51)
                AppManager.getInstance().addNewContact(contactUri, new ResultListener() {
                    @Override
                    public void onResult(boolean success) {
                        if (!success){
                            Toast.makeText(ChatActivity.this, "Could not find that phone number.", Toast.LENGTH_SHORT).show();
                        }

                        updateContactName();
                    }
                });*/
            }
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
    }
}
 
Example 20
Project: alerta-fraude   File: LocalFilesystem.java   View Source Code Vote up 4 votes
@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;
}