Google Drive uploading a file, and reading a file - java

.Net guy working on a java app
I am uploading using the following example as my starting point ( I have this working). This shows using FileContent needing a java.io.File which does not contain the actual file only a pointer to the actual file.
We are uploading from a web site and attempting to insert into the drive, I would prefer to do this using a memory Stream like the .Net example. I cannot see that in looking at the FileContent class. So my questing is: Is there a way to insert a file in Google drive that is in memory and not first on the hard drive?
private static File insertFile(Drive service, String title, String description,
String parentId, String mimeType, String filename) {
// File's metadata.
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);
// Set the parent folder.
if (parentId != null && parentId.length() > 0) {
body.setParents(
Arrays.asList(new ParentReference().setId(parentId)));
}
// File's content.
java.io.File fileContent = new java.io.File(filename);
FileContent mediaContent = new FileContent(mimeType, fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
// Uncomment the following line to print the File ID.
// System.out.println("File ID: " + file.getId());
return file;
} catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}

Override the AbstractInputStream build your own FileContent
package com;
import java.io.IOException;
import java.io.InputStream;
import com.google.api.client.http.AbstractInputStreamContent;
import com.google.api.client.util.Preconditions;
public class FileContent extends AbstractInputStreamContent {
private InputStream inputStream = null;
private long inputLength = 0;
public FileContent(String type, InputStream pInputStream) throws IOException {
super(type);
this.inputStream = Preconditions.checkNotNull(pInputStream);
this.inputLength = this.inputStream.available();
}
public long getLength() throws IOException {
return this.inputLength;
}
public boolean retrySupported() {
return false;
}
#Override
public InputStream getInputStream() throws IOException {
return this.inputStream;
}
}

Related

Printing contents of an imported class to console in java

I'm programming in an online IDE (it is studio.code.org) (For a programming course). I would like to switch to a local IDE, but the online IDE uses some imports that are unavailable to download, but can be used in the code that has been written in the online IDE. This is in java. To make this a more general form of question that applies to (and will help) most people:
This is in java. I'm trying to print the contents of a file out in the console whose path is unknown, but is used as an import. Is it possible? If so, what code do I need to run to print the file out in console (from where I can copy paste it and use it elsewhere).
Here's the source code for something I tried to make this happen (but it didn't work, I'll show what output I got from the console below the code):
import java.io.*;
import org.code.neighborhood.Painter;
public class MyNeighborhood {
public static void main(String[] args) {
try {
Class<?> cls = Class.forName("org.code.neighborhood.Painter");
String fileName = cls.getName().replace('.', File.separatorChar) + ".class";
File file = new File(fileName);
System.out.println("File path: " + file.getAbsolutePath());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
fis.read(buffer);
fis.close();
System.out.println(new String(buffer));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output from console:
[JAVALAB] Connecting...
[JAVALAB] Compiling...
[JAVALAB] Compilation successful.
[JAVALAB] Running...
File path: /tmp/org/code/neighborhood/Painter.class
As you may have noticed I have found a file, but it is empty, although I know that the real file that is being imported is certainly not empty.
I do have read access to the system as well since I am able to navigate the root folder by using the code below:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
boolean readContent = false; // change this to true to read file content, false to read file names
File directory = new File("/");
if (readContent) {
String fileName = "";
readFileContent(directory, fileName);
} else {
String[] fileNames = readFileNames(directory);
if (fileNames == null) {
System.out.println("Directory not found.");
} else {
System.out.println("Files in the directory:");
for (String fileName : fileNames) {
File file = new File(directory, fileName);
if (file.isDirectory()) {
System.out.println("Directory: " + fileName);
} else if (file.isFile()) {
System.out.println("File: " + fileName);
}
}
}
}
}
private static void readFileContent(File directory, String fileName) {
File file = new File(directory, fileName);
if (file.isFile()) {
try (FileReader reader = new FileReader(file)) {
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
} else {
System.out.println("File not found.");
}
}
private static String[] readFileNames(File directory) {
if (directory.isDirectory()) {
return directory.list();
}
return null;
}
}

unable to unzip the zip file on linux environment

I am stuck in this issue very badly. I was trying to unzip the zip file using java. I need to upload a zip file using jsp. In controller it accepts Multipart file. Then I have to unzip this file to some location say a temp directory. I did mulipartFile.transferTo('temp zipfile location'), to place a zip file. Under this location zip file will always be replaced. This (zipcopy) would be the source of zip file to be unziped later.. below is code snippet..
String zipcopy = env.getProperty("zipFileCopier");
file.transferTo(new File(zipcopy));
file is of type Multipart.
This is running well on windows environment. No issues at all. I changed the path in application.properties for Linux environment. What I found is -- it is just NOT creating any unziped directories in temp directory. I call unzip code here :
unziputility.unzip(zipcopy, destTemp);
File extractedDir = new File(destTemp+File.separator+multipartFileName+File.separator+"local");
if(extractedDir!=null && extractedDir.exists() && extractedDir.isDirectory()) {
System.out.println("TEST");
//business logic
}
TEST is not getting printed in Linux env. Also note that above code is in try catch block with ex.printstackTrace method used. However no exception is seen caught. Here is my UnzipUtility class:
UnzipUtility
package abc.xyz.re.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.springframework.stereotype.Component;
#Component
public class UnzipUtility {
private static final int BUFFER_SIZE = 9096;
public void unzip(String zipFilePath, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String entryName = entry.getName();
String filePath = destDirectory + File.separator + entryName;
if (!entry.isDirectory()) {
extractFile(zipIn, filePath);
} else {
File dir = new File(filePath);
dir.mkdirs();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
}
above UnzipUtility when replaced with lingala zip4j..same issue. https://github.com/srikanth-lingala/zip4j.
application.properties
uploadDestTemp = /opt/temp
destDirectory = /opt/apache-tomcat-7.0.39/webapps/ROOT/root_/contents/crbt_tones
zipFileCopier = /opt/zip_download/zipfile.zip
in above application.properties file, uploadDestTemp is already created. Also zipFileCopier directory with zipfile.zip file is created
I re-tested this case by making sample code only for unziping the zip file from one location to other. Again it ran perfect in Windows. But failed in Linux. code below:
package package123;
public class Test4 {
public static void main(String[] args) {
System.out.println("testing...");
try {
UnzipUtility unzipUtility = new UnzipUtility();
String unzipLocation = "/opt/temp";
String zipFilePath = "/opt/zip_download/zipfile.zip";
unzipUtility.unzip(zipFilePath, unzipLocation);
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
someone please help me to resolve this issue. kindly tell me why I am not able to use this code on my production Linux environment.

Process a ZIPped XML file in Java [duplicate]

I am trying to create a simple java program which reads and extracts the content from the file(s) inside zip file. Zip file contains 3 files (txt, pdf, docx). I need to read the contents of all these files and I am using Apache Tika for this purpose.
Can somebody help me out here to achieve the functionality. I have tried this so far but no success
Code Snippet
public class SampleZipExtract {
public static void main(String[] args) {
List<String> tempString = new ArrayList<String>();
StringBuffer sbf = new StringBuffer();
File file = new File("C:\\Users\\xxx\\Desktop\\abc.zip");
InputStream input;
try {
input = new FileInputStream(file);
ZipInputStream zip = new ZipInputStream(input);
ZipEntry entry = zip.getNextEntry();
BodyContentHandler textHandler = new BodyContentHandler();
Metadata metadata = new Metadata();
Parser parser = new AutoDetectParser();
while (entry!= null){
if(entry.getName().endsWith(".txt") ||
entry.getName().endsWith(".pdf")||
entry.getName().endsWith(".docx")){
System.out.println("entry=" + entry.getName() + " " + entry.getSize());
parser.parse(input, textHandler, metadata, new ParseContext());
tempString.add(textHandler.toString());
}
}
zip.close();
input.close();
for (String text : tempString) {
System.out.println("Apache Tika - Converted input string : " + text);
sbf.append(text);
System.out.println("Final text from all the three files " + sbf.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TikaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If you're wondering how to get the file content from each ZipEntry it's actually quite simple. Here's a sample code:
public static void main(String[] args) throws IOException {
ZipFile zipFile = new ZipFile("C:/test.zip");
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()){
ZipEntry entry = entries.nextElement();
InputStream stream = zipFile.getInputStream(entry);
}
}
Once you have the InputStream you can read it however you want.
As of Java 7, the NIO АРI provides a better and more generic way of accessing the contents of ZIP or JAR files. Actually, it is now a unified API which allows you to treat ZIP files exactly like normal files.
In order to extract all of the files contained inside of a ZIP file in this API, you'd do as shown below.
In Java 8
private void extractAll(URI fromZip, Path toDirectory) throws IOException {
FileSystems.newFileSystem(fromZip, Collections.emptyMap())
.getRootDirectories()
.forEach(root -> {
// in a full implementation, you'd have to
// handle directories
Files.walk(root).forEach(path -> Files.copy(path, toDirectory));
});
}
In Java 7
private void extractAll(URI fromZip, Path toDirectory) throws IOException {
FileSystem zipFs = FileSystems.newFileSystem(fromZip, Collections.emptyMap());
for (Path root : zipFs.getRootDirectories()) {
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
// You can do anything you want with the path here
Files.copy(file, toDirectory);
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
// In a full implementation, you'd need to create each
// sub-directory of the destination directory before
// copying files into it
return super.preVisitDirectory(dir, attrs);
}
});
}
}
Because of the condition in while, the loop might never break:
while (entry != null) {
// If entry never becomes null here, loop will never break.
}
Instead of the null check there, you can try this:
ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
// Rest of your code
}
Sample code you can use to let Tika take care of container files for you.
http://wiki.apache.org/tika/RecursiveMetadata
Form what I can tell, the accepted solution will not work for cases where there are nested zip files. Tika, however will take care of such situations as well.
My way of achieving this is by creating ZipInputStream wrapping class that would handle that would provide only the stream of current entry:
The wrapper class:
public class ZippedFileInputStream extends InputStream {
private ZipInputStream is;
public ZippedFileInputStream(ZipInputStream is){
this.is = is;
}
#Override
public int read() throws IOException {
return is.read();
}
#Override
public void close() throws IOException {
is.closeEntry();
}
}
The use of it:
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("SomeFile.zip"));
while((entry = zipInputStream.getNextEntry())!= null) {
ZippedFileInputStream archivedFileInputStream = new ZippedFileInputStream(zipInputStream);
//... perform whatever logic you want here with ZippedFileInputStream
// note that this will only close the current entry stream and not the ZipInputStream
archivedFileInputStream.close();
}
zipInputStream.close();
One advantage of this approach: InputStreams are passed as an arguments to methods that process them and those methods have a tendency to immediately close the input stream after they are done with it.
i did mine like this and remember to change url or zip files
jdk 15
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.io.*;
import java.util.*;
import java.nio.file.Paths;
class Main {
public static void main(String[] args) throws MalformedURLException,FileNotFoundException,IOException{
String url,kfile;
Scanner getkw = new Scanner(System.in);
System.out.println(" Please Paste Url ::");
url = getkw.nextLine();
System.out.println("Please enter name of file you want to save as :: ");
kfile = getkw.nextLine();
getkw.close();
Main Dinit = new Main();
System.out.println(Dinit.dloader(url, kfile));
ZipFile Vanilla = new ZipFile(new File("Vanilla.zip"));
Enumeration<? extends ZipEntry> entries = Vanilla.entries();
while(entries.hasMoreElements()){
ZipEntry entry = entries.nextElement();
// String nextr = entries.nextElement();
InputStream stream = Vanilla.getInputStream(entry);
FileInputStream inpure= new FileInputStream("Vanilla.zip");
FileOutputStream outter = new FileOutputStream(new File(entry.toString()));
outter.write(inpure.readAllBytes());
outter.close();
}
}
private String dloader(String kurl, String fname)throws IOException{
String status ="";
try {
URL url = new URL("URL here");
FileOutputStream out = new FileOutputStream(new File("Vanilla.zip")); // Output File
out.write(url.openStream().readAllBytes());
out.close();
} catch (MalformedURLException e) {
status = "Status: MalformedURLException Occured";
}catch (IOException e) {
status = "Status: IOexception Occured";
}finally{
status = "Status: Good";}
String path="\\tkwgter5834\\";
extractor(fname,"tkwgter5834",path);
return status;
}
private String extractor(String fname,String dir,String path){
File folder = new File(dir);
if(!folder.exists()){
folder.mkdir();
}
return "";
}
}

How to add Progress bar to File Copy in Java

so I have class that is used to copy all of a specific file type from one directory to another directory. This class does work, but I am curious on what would be the best method of adding a progress bar to let the users know how far along in copying all the files.
So my question is, what would be the best method of adding a progress bar to this class. As you may see, there is no GUI being made by this class as it stands.
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFilesFromType
{
public static void main(File SourcePath, File DestPath)
{
new CopyFilesFromType().copy("tif", SourcePath.toString(), DestPath.toString());
}
private FileTypeOrFolderFilter filter = null;
private void copy(final String fileType, String fromPath, String outputPath)
{
filter = new FileTypeOrFolderFilter(fileType);
File currentFolder = new File(fromPath);
File outputFolder = new File(outputPath);
scanFolder(fileType, currentFolder, outputFolder);
}
private void scanFolder(final String fileType, File currentFolder, File outputFolder)
{
System.out.println("Scanning folder [" + currentFolder + "]...");
File[] files = currentFolder.listFiles(filter);
for (File file : files) {
if (file.isDirectory()) {
scanFolder(fileType, file, outputFolder);
} else {
copy(file, outputFolder);
}
}
}
private void copy(File file, File outputFolder)
{
try {
System.out.println("\tCopying [" + file + "] to folder [" + outputFolder + "]...");
InputStream input = new FileInputStream(file);
OutputStream out = new FileOutputStream(new File(outputFolder + File.separator + file.getName()));
byte data[] = new byte[input.available()];
input.read(data);
out.write(data);
out.flush();
out.close();
input.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private final class FileTypeOrFolderFilter implements FileFilter
{
private final String fileType;
private FileTypeOrFolderFilter(String fileType)
{
this.fileType = fileType;
}
public boolean accept(File pathname)
{
return pathname.getName().endsWith("." + fileType) || pathname.isDirectory();
}
}
}
Wrap the FileInputStream in a javax.swing.ProgressMonitorInputStream.

How to unzip a zip folder containing different file formats using Java

I need to unzip a zipped directory containing different files' format like .txt, .xml, .xls etc.
I am able to unzip if the directory contains only .txt files but it fails with other files format. Below is the program that I am using and after a bit of googling, all I saw was similar approach -
import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipUtils {
public static void extractFile(InputStream inStream, OutputStream outStream) throws IOException {
byte[] buf = new byte[1024];
int l;
while ((l = inStream.read(buf)) >= 0) {
outStream.write(buf, 0, l);
}
inStream.close();
outStream.close();
}
public static void main(String[] args) {
Enumeration enumEntries;
ZipFile zip;
try {
zip = new ZipFile("myzip.zip");
enumEntries = zip.entries();
while (enumEntries.hasMoreElements()) {
ZipEntry zipentry = (ZipEntry) enumEntries.nextElement();
if (zipentry.isDirectory()) {
System.out.println("Name of Extract directory : " + zipentry.getName());
(new File(zipentry.getName())).mkdir();
continue;
}
System.out.println("Name of Extract fille : " + zipentry.getName());
extractFile(zip.getInputStream(zipentry), new FileOutputStream(zipentry.getName()));
}
zip.close();
} catch (IOException ioe) {
System.out.println("There is an IoException Occured :" + ioe);
ioe.printStackTrace();
}
}
}
Throws the below exception -
There is an IoException Occured :java.io.FileNotFoundException: myzip\abc.xml (The system cannot find the path specified)
java.io.FileNotFoundException: myzip\abc.xml (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:104)
at updaterunresults.ZipUtils.main(ZipUtils.java:43)
When you try to open the file that is going to contain the extracted content, the error occurs.
This is because the myzip folder is not available.
So check if it indeed is not available and create it before extracting the zip:
File outputDirectory = new File("myzip");
if(!outputDirectory.exists()){
outputDirectory.mkdir();
}
As #Perception pointed out in the comments: The output location is relative to the active/working directory. This is probably not very convenient, so you might want to add the extraction location to the location of the extracted files:
File outputLocation = new File(outputDirectory, zipentry.getName());
extractFile(zip.getInputStream(zipentry), new FileOutputStream(outputLocation));
(of course you need also add outputLocation to the directory creation code)
This is a good example in which he showed to unzip all the formats (pdf, txt etc) have look its quite
or you can use this code might work (i haven't tried this)
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipUtils
{
private static final int BUFFER_SIZE = 4096;
private static void extractFile(ZipInputStream in, File outdir, String name) throws IOException
{
byte[] buffer = new byte[BUFFER_SIZE];
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir,name)));
int count = -1;
while ((count = in.read(buffer)) != -1)
out.write(buffer, 0, count);
out.close();
}
private static void mkdirs(File outdir,String path)
{
File d = new File(outdir, path);
if( !d.exists() )
d.mkdirs();
}
private static String dirpart(String name)
{
int s = name.lastIndexOf( File.separatorChar );
return s == -1 ? null : name.substring( 0, s );
}
/***
* Extract zipfile to outdir with complete directory structure
* #param zipfile Input .zip file
* #param outdir Output directory
*/
public static void extract(File zipfile, File outdir)
{
try
{
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipfile));
ZipEntry entry;
String name, dir;
while ((entry = zin.getNextEntry()) != null)
{
name = entry.getName();
if( entry.isDirectory() )
{
mkdirs(outdir,name);
continue;
}
/* this part is necessary because file entry can come before
* directory entry where is file located
* i.e.:
* /foo/foo.txt
* /foo/
*/
dir = dirpart(name);
if( dir != null )
mkdirs(outdir,dir);
extractFile(zin, outdir, name);
}
zin.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Regards

Categories

Resources