I wanna to know how to add a folder in the apk.don't give me a solution about using the compress software directly. The apk was recompiled by the 'apktool.jar'. I need some code to achieve this problem. Hope one can solve my question as soon as possible.Thank you~
public static int zipMetaInfFolderToApk(String apkName, String folderName) throws IOException {
if(!new File(apkName).exists()){
return ConstantValue.ISQUESTION;
}
String zipName = apkName.substring(0, apkName.lastIndexOf(".")) + "."
+ "zip";
String bak_zipName = apkName.substring(0, apkName.lastIndexOf("."))
+ "_bak." + "zip";
FileUtils.renameFile(apkName, zipName);
ZipFile war = new ZipFile(zipName);
ZipOutputStream append = new ZipOutputStream(new FileOutputStream(
bak_zipName));
Enumeration<? extends ZipEntry> entries = war.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
System.out.println("copy: " + e.getName());
append.putNextEntry(e);
if (!e.isDirectory()) {
copy(war.getInputStream(e), append);
}
append.closeEntry();
}
String name = "";
if(folderName.equals("")){
name = "META-INF/" + folderName;
}else{
name = "META-INF/" + folderName + "/";
}
ZipEntry e = new ZipEntry(name);
try{
append.putNextEntry(e);
}catch(ZipException e1){
append.closeEntry();
war.close();
append.close();
FileUtils.renameFile(zipName,apkName);
FileUtils.deleteFolder(bak_zipName);
e1.printStackTrace();
return ConstantValue.ISQUESTION;
}
append.closeEntry();
war.close();
append.close();
FileUtils.deleteFolder(zipName);
FileUtils.renameFile(bak_zipName, apkName);
return ConstantValue.ISNORMAL;
}
Related
public List<string> Upload(HttpPostedFileBase[] files)
{
//string size = fc["size"];
int sizeResize = AppSettings.Company.ChieuRongToiDaCuaHinhUpload ?? 1500;
//if (!string.IsNullOrEmpty(size))
//{
// int.TryParse(size, out sizeResize);
//}
List<string> fileNames = new List<string>();
try
{
// Duyệt qua các file được gởi lên phía client
foreach (HttpPostedFileBase file in files)
{
//Lấy ra file trong list các file gởi lên
//HttpPostedFileBase file = Request.Files[fileName];
//Save file content goes here
if (file != null && file.ContentLength > 0)
{
//Định nghĩa đường dẫn lưu file trên server
//ở đây mình lưu tại đường dẫn yourdomain.com/Uploads/
var originalDirectory = new DirectoryInfo(string.Format("{0}Uploads\\{1}\\", Server.MapPath(#"\"),"files"));
//Lưu trữ hình ảnh theo từng tháng trong năm
string pathString = System.IO.Path.Combine(originalDirectory.ToString(), DateTime.Now.ToString("yyyy-MM"));
bool isExists = System.IO.Directory.Exists(pathString);
if (!isExists) System.IO.Directory.CreateDirectory(pathString);
var path = string.Format("{0}\\{1}", pathString, Common.Tools.StringTools.ConvertToUnSignNoneDotSign(file.FileName));
string newFileName = file.FileName;
//lấy đường dẫn lưu file sau khi kiểm tra tên file trên server có tồn tại hay không
//thư mục files nằm trong CKFinder để quản lý file
var newPath = GetNewPathForDupes(path, ref newFileName);
string serverPath = string.Format("/{0}/{1}/{2}/{3}", "Uploads","files", DateTime.Now.ToString("yyyy-MM"), newFileName);
//nếu là loại file hình thì resize, còn lại khỏi
if(file.ContentType.Contains("image"))
{
//Lưu hình ảnh Resize từ file sử dụng file.InputStream
SaveResizeImage(Image.FromStream(file.InputStream), sizeResize, newPath);
//Tạo hình Thumbnail
StringTools.CreateThumbnail(newFileName, pathString, withThumbnailImage, withThumbnailImage, true);
}
else
{
file.SaveAs(newPath);
}
fileNames.Add(serverPath);
//fileNames.Add("LocalPath: " + newPath + "<br/>ServerPath: " + serverPath);
}
}
}
catch (Exception ex)
{
TempData["e"] = ex.Message;
logger.Error(ex.Message);
}
TempData["file"] = fileNames;
return fileNames;
//return RedirectToAction("Index", "Home");
//return RedirectToAction("Edit", "VL_TinTuyenDung");
}
I have windows application that can access files from setting.ini file I modified it and get access to them from my code. but still getting this error like 'C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
here is my setting.ini file code :
[UserDetail]
UserID=xxxxxxx
PassWord=xxxxxxxx
[Connection]
contact=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls
DebitISE=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE 1.xls
DebitLKP=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls
[FilePath]
DebitISEClient=C:
[FileName]
DebitISEClient=Contact_06-07-2015.txt
and here my code for accessing this files from ini file :
private void button1_Click(object sender, EventArgs e)
{
string filepath = txtpayoutfile.Text;
string message = "";
string mobileno = "";
string name = "";
DataSet dsmaster = new DataSet();
string filepathc = ini.IniReadValue("Connection", "contact");
if (filepath == "")
{
MessageBox.Show("Import Contact File");
this.Show();
}
if (Path.GetExtension(filepath) == ".xls")
{
oledbConn1 = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepathc + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(filepath) == ".xlsx")
{
oledbConn1 = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepathc + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
oledbConn1.Open(); ////exception occurs here
if (Path.GetExtension(filepath) == ".xls")
{
oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(filepath) == ".xlsx")
{
oledbConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
OleDbCommand cmdoledb = new OleDbCommand("Select * from [Sheet1$3:3000]", oledbConn);
OleDbDataAdapter daoledb = new OleDbDataAdapter(cmdoledb);
DataTable dt = new DataTable();
daoledb.Fill(dt);
}
I was toying with the idea of rewriting some existing bash scripts in kotlin script.
One of the scripts has a section that unzips all the files in a directory. In bash:
unzip *.zip
Is there a nice way to unzip a file(s) in kotlin script?
The easiest way is to just use exec unzip (assuming that the name of your zip file is stored in zipFileName variable):
ProcessBuilder()
.command("unzip", zipFileName)
.redirectError(ProcessBuilder.Redirect.INHERIT)
.redirectOutput(ProcessBuilder.Redirect.INHERIT)
.start()
.waitFor()
The different approach, that is more portable (it will run on any OS and does not require unzip executable to be present), but somewhat less feature-full (it will not restore Unix permissions), is to do unzipping in code:
import java.io.File
import java.util.zip.ZipFile
ZipFile(zipFileName).use { zip ->
zip.entries().asSequence().forEach { entry ->
zip.getInputStream(entry).use { input ->
File(entry.name).outputStream().use { output ->
input.copyTo(output)
}
}
}
}
If you need to scan all *.zip file, then you can do it like this:
File(".").list { _, name -> name.endsWith(".zip") }?.forEach { zipFileName ->
// any of the above approaches
}
or like this:
import java.nio.file.*
Files.newDirectoryStream(Paths.get("."), "*.zip").forEach { path ->
val zipFileName = path.toString()
// any of the above approaches
}
this code is for unziping from Assets
1.for unzping first u need InputStream
2.put it in ZipInputStream
3.if directory is not exist u have to make by .mkdirs()
private val BUFFER_SIZE = 8192//2048;
private val SDPath = Environment.getExternalStorageDirectory().absolutePath
private val unzipPath = "$SDPath/temp/zipunzipFile/unzip/"
var count: Int
val buffer = ByteArray(BUFFER_SIZE)
val context: Context = this
val am = context.getAssets()
val stream = context.getAssets().open("raw.zip")
try {
ZipInputStream(stream).use { zis ->
var ze: ZipEntry
while (zis.nextEntry.also { ze = it } != null) {
var fileName = ze.name
fileName = fileName.substring(fileName.indexOf("/") + 1)
val file = File(unzipPath, fileName)
val dir = if (ze.isDirectory) file else file.getParentFile()
if (!dir.isDirectory() && !dir.mkdirs())
throw FileNotFoundException("Invalid path: " + dir.getAbsolutePath())
if (ze.isDirectory) continue
val fout = FileOutputStream(file)
try {
while ( zis.read(buffer).also { count = it } != -1)
fout.write(buffer, 0, count)
} finally {
val fout : FileOutputStream =openFileOutput(fileName, Context.MODE_PRIVATE)
fout.close()
}
}
for unziping from externalStorage:
private val sourceFile= "$SDPath/unzipFile/data/"
ZipInputStream zis = null;
try {
zis = new ZipInputStream(new BufferedInputStream(new
FileInputStream(sourceFile)));
ZipEntry ze;
int count;
byte[] buffer = new byte[BUFFER_SIZE];
while ((ze = zis.getNextEntry()) != null) {
String fileName = ze.getName();
fileName = fileName.substring(fileName.indexOf("/") + 1);
File file = new File(destinationFolder, fileName);
File dir = ze.isDirectory() ? file : file.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs())
throw new FileNotFoundException("Invalid path: " +
dir.getAbsolutePath());
if (ze.isDirectory()) continue;
FileOutputStream fout = new FileOutputStream(file);
try {
while ((count = zis.read(buffer)) != -1)
fout.write(buffer, 0, count);
} finally {
fout.close();
}
}
} catch (IOException ioe) {
Log.d(TAG, ioe.getMessage());
return false;
} finally {
if (zis != null)
try {
zis.close();
} catch (IOException e) {
}
}
return true;
I'm trying to use the built in upload file of CKEditor, it works with my MVC5 project, but it doesn't work with my MVC6 project, the code for uploading the file is correct, I've tested it, and it actually upload the file to the server, but it doesn't populate the form with the URL and image information, here's the code for my MVC5 project that works:
public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor,
string langCode)
{
string vImagePath = String.Empty;
string vMessage = String.Empty;
string vFilePath = String.Empty;
string vOutput = String.Empty;
try
{
if (upload != null && upload.ContentLength > 0)
{
var vFileName = DateTime.Now.ToString("yyyyMMdd-HHMMssff") + " - " + Path.GetFileName(upload.FileName);
var vFolderPath = Server.MapPath("/Upload/");
if (!Directory.Exists(vFolderPath))
{
Directory.CreateDirectory(vFolderPath);
}
vFilePath = Path.Combine(vFolderPath, vFileName);
upload.SaveAs(vFilePath);
vImagePath = Url.Content("/Upload/" + vFileName);
vMessage = "The file uploaded successfully.";
}
}
catch(Exception e)
{
vMessage = "There was an issue uploading:" + e.Message;
}
vOutput = #"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + vImagePath + "\", \"" + vMessage + "\");</script></body></html>";
return Content(vOutput);
}
And here is the code for MVC6 project that doesn't work:
public async Task<ActionResult> UploadImage(IFormFile upload, string CKEditorFuncNum, string CKEditor,
string langCode)
{
string vImagePath = String.Empty;
string vMessage = String.Empty;
string vFilePath = String.Empty;
string vOutput = String.Empty;
try
{
if (upload != null && upload.Length > 0)
{
var vFileName = DateTime.Now.ToString("yyyyMMdd-HHMMssff") + " - " + ContentDispositionHeaderValue.Parse(upload.ContentDisposition).FileName.Trim('"');
var vFolderPath = Path.Combine(_environment.WebRootPath, "Files", "ArticleUploads");
if (!Directory.Exists(vFolderPath))
{
Directory.CreateDirectory(vFolderPath);
}
vFilePath = Path.Combine(vFolderPath, vFileName);
await upload.SaveAsAsync(vFilePath);
vImagePath = Url.Content("/Files/ArticleUploads/" + vFileName);
vMessage = "The file uploaded successfully.";
}
}
catch (Exception e)
{
vMessage = "There was an issue uploading:" + e.Message;
}
vOutput = #"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + vImagePath + "\", \"" + vMessage + "\");</script></body></html>";
return Content(vOutput);
}
And in CKEditor config file I have:
config.filebrowserImageUploadUrl = '/Admin/Article/UploadImage';
I've inspected the variables, and they send the same value, also worth to note that I'm using the same version of CKEditor, so that can't be the problem, I'd appreciate any help on this.
If the file gets uploaded and you don't see the image gets populated, I guess there should be some problem with the way you return your content, since you are returning html, try to specify your content type, like so:
return Content(vOutput, "text/html");
If that didn't solve your problem, you need to provide more information, tell us what exactly you get from this action in JavaScript side.
I could get the handle to the google text doc i needed. I am now stuck at how to read the contents.
My code looks like:
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(Constants.CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
oauthParameters.setOAuthToken(Constants.ACCESS_TOKEN);
oauthParameters.setOAuthTokenSecret(Constants.ACCESS_TOKEN_SECRET);
DocsService client = new DocsService("sakshum-YourAppName-v1");
client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentQuery dquery = new DocumentQuery(feedUrl);
dquery.setTitleQuery("blood_donor_verification_template_dev");
dquery.setTitleExact(true);
dquery.setMaxResults(10);
DocumentListFeed resultFeed = client.getFeed(dquery, DocumentListFeed.class);
System.out.println("feed size:" + resultFeed.getEntries().size());
String emailBody = "";
for (DocumentListEntry entry : resultFeed.getEntries()) {
System.out.println(entry.getPlainTextContent());
emailBody = entry.getPlainTextContent();
}
Plz note that entry.getPlainTextContent() does not work and throws object not TextContent type exception
finally i solved it as:
for (DocumentListEntry entry : resultFeed.getEntries()) {
String docId = entry.getDocId();
String docType = entry.getType();
URL exportUrl =
new URL("https://docs.google.com/feeds/download/" + docType
+ "s/Export?docID=" + docId + "&exportFormat=html");
MediaContent mc = new MediaContent();
mc.setUri(exportUrl.toString());
MediaSource ms = client.getMedia(mc);
InputStream inStream = null;
try {
inStream = ms.getInputStream();
int c;
while ((c = inStream.read()) != -1) {
emailBody.append((char)c);
}
} finally {
if (inStream != null) {
inStream.close();
}
}
}