Copying all files of an external drive to pc in minimum time - java

I am trying to copy all the files of an external drive to a specific location on my pc.
Here is my code :-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class mod
{
public static void main(String[] args)
{
String[] letters = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I"};
File[] drives = new File[letters.length];
int l;File files[]=null;boolean pluggedIn=false;
FileInputStream fis=null;
FileOutputStream fos=null;
boolean[] isDrive = new boolean[letters.length];
for (int i = 0; i < letters.length; ++i)
{
drives[i] = new File(letters[i] + ":/");
isDrive[i] = drives[i].canRead();
}
System.out.println("FindDrive: waiting for devices...");
File file;
while (true)
{
try
{
for (int i = 0; i < letters.length; ++i)
{
pluggedIn = drives[i].canRead();
if (pluggedIn != isDrive[i])
{
if (pluggedIn)
{
System.out.println("Drive " + letters[i] + " has been plugged in");
files = drives[i].getAbsoluteFile().listFiles();
for (l = 0; l < files.length; l++)
{
if (files[l].isFile())
{
file = new File("G://copied//" + files[l].getName());
fis = new FileInputStream(drives[i].getAbsolutePath() + files[l].getName());
fos = new FileOutputStream(file);
byte[] buffer = new byte[99999999];
int n;
while ((n = fis.read(buffer)) != -1)
{
fos.write(buffer, 0, n);
}
fis.close();
fos.close();
}
else
{
func(files[l].getAbsoluteFile(), "G://copied");
}
if(l==files.length-1)
{
System.out.print("copy complete");
}
}
}
else
{
System.out.println("Drive " + letters[i] + " has been unplugged");
}
isDrive[i] = pluggedIn;
}
}
Thread.sleep(3000);
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
}
}
public static void func(File dir, String path) throws IOException
{
File file = new File(path + "//" + dir.getName());
file.mkdir();
File[] files = dir.listFiles();
FileInputStream fis=null;
FileOutputStream fos=null;
File file1;
for (int i = 0; i < files.length; i++)
{
if (files[i].isFile())
{
file1 = new File(file.getAbsolutePath() + "//" + files[i].getName());
try
{
file1.createNewFile();
fis = new FileInputStream(files[i]);
fos = new FileOutputStream(file1);
while (true)
{
byte[] buffer = new byte[99999999];
int n;
while ((n = fis.read(buffer)) != -1)
{
fos.write(buffer, 0, n);
}
fis.close();
fos.close();
}
} catch (FileNotFoundException e) {} catch (IOException e) {}
}
else
{
func(files[i], file.getAbsolutePath());
}
}
}
}
It is working fine.But it is taking too long to copy large files.
My question is that is there any way by which the copy time can be reduced?

Related

how to stop socket to close automatically after sending files

I am making an app which requires socket to send files from one to another Well i can successfully send and receive any file from one device to another but the problem is my socket connection closes itself automatically after file transfer. I also tried removing socket.close() from both sides but it still closes itself
Here is the server's code
try {
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(files.size());
dos.flush();
for(int i = 0 ; i < files.size();i++){
dos.writeUTF(files.get(i).getName());
dos.flush();
}
int n = 0;
byte[]buf = new byte[4092];
for(int i =0; i < files.size(); i++){
if (name == null){
dos.writeUTF(files.get(i).getName());
}else {
dos.writeUTF(filesName.get(i) + ".apk");
}
dos.writeLong(files.get(i).length());
FileInputStream fis = new FileInputStream(files.get(i));
while((n =fis.read(buf)) != -1){
dos.write(buf,0,n);
dos.flush();
}
}
dos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
And Here is the Client's code
try {
socket = new Socket(dstAddress, dstPort);
bufferSize = socket.getReceiveBufferSize();
in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
int number = dis.readInt();
ArrayList<File>files = new ArrayList<File>(number);
for(int i = 0; i< number;i++){
File file = new File(dis.readUTF());
files.add(file);
}
int n = 0;
byte[]buf = new byte[4092];
for(int i = 0; i < files.size();i++){
int fileeesizee = 0;
publishProgress(String.valueOf(0));
String filename = dis.readUTF();
long fileSize = dis.readLong();
recyclername.add(filename);
recyclersize.add(android.text.format.Formatter.formatFileSize(test2.this, fileSize));
recyclerimg.add(filename);
final File f = new File(Environment.getExternalStorageDirectory()+"/SharePlus/.data/"+filename);
FileOutputStream fos = new FileOutputStream(f);
while (fileSize > 0 && (n = dis.read(buf, 0, (int)Math.min(buf.length, fileSize))) != -1)
{
fos.write(buf,0,n);
fileSize -= n;
fileeesizee+=n;
if (fileSize==0){
}else{
publishProgress(""+(int)((fileeesizee * 100) / fileSize));
}
}
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
Log.d("d", "1 catch = " + e.getMessage());
final String eMsg = "Something wrong: " + e.getMessage();
test2.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(test2.this, eMsg, Toast.LENGTH_LONG).show();
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
Log.d("d", "2 catch = " + e.getMessage());
e.printStackTrace();
}
}
}
dos.close();
Closing a stream closes the socket too.

Saving a 2-dimensional Sting Array in a .txt file and load from it

I want to save a 2-dimensional String Array in a .txt file and load it from it in my app. The Array should be editable and expandable in the app. I am not really experienced with BufferedWriter, BufferedReader, FileInputStream and FileOutputStream and things like this.
I have problems with this code: The BufferedWriter and BufferedReader throws a NullPointerException and I don't know why. Or does everyone know a possibillity to do this with FileInputStream and FileoutputStream?
public String path =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFile";
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(path + "/savedFile.txt");
public static void Save(File file, String[][] list)
{
BufferedWriter writer = null;
StringBuilder builder = new StringBuilder();
try
{
writer = new BufferedWriter(new FileWriter(file));
}
catch (IOException e) {e.printStackTrace();}
try
{
try
{
for(int i = 0; i < list.length; i++)
{
for(int j = 0; j < list[i].length; j++)
{
builder.append(list[i][j]+"");
if(j < list.length - 1)
builder.append(",");
}
builder.append("\n");
}
}
catch (Exception e) {e.printStackTrace();}
}
finally
{
try
{
writer.write(builder.toString());
writer.close();
}
catch (IOException e) {e.printStackTrace();}
}
}
public static String[][] Load(File file)
{
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
}
catch (FileNotFoundException e) {e.printStackTrace();}
String test;
String[][] array = new String[4][2]; //the indexs are for a specific example; it should be expandable, but I solve that myself
String line;
int row = 0;
try
{
while ((line = reader.readLine()) != null) {
String[] cols = line.split(",");
int col = 0;
for (String c : cols) {
array[row][col] = c;
col++;
}
row++;
}
}
catch (IOException e) {e.printStackTrace();}
return array;
}
I think that the problem would be with the scope of variables in multiple braces you've used. try this code:
public static void Save(File file, String[][] list) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < list.length; i++) {
for (int j = 0; j < list[i].length; j++) {
builder.append(list[i][j] + "");
if (j < list.length - 1) {
builder.append(",");
}
}
builder.append("\n");
}
try {
Writer writer = new BufferedWriter(new FileWriter(file));
try {
writer.write(builder.toString());
} finally {
writer.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

Unable to write the .csv into mobile storage in android

I have converted the db file into csv file and worked perfectly in android. But I manually deleted the csv file from storage location and try to run the same code. but I am unable to write the file into the same location. No exception noticed.
The code used is as follows:
public void exportTopic() {
int rowCount, colCount;
int i, j;
Cursor c=null;
SQLHelper helperr=null;
try {
helperr=new SQLHelper(getActivity());
c = helperr.getAllTopics();
Log.d("exportPath", sdCardDir.getPath());
String filename = "MyBackUp.csv";
File CsvFile = new File(sdCardDir, filename);
FileWriter fw = new FileWriter(CsvFile);
BufferedWriter bw = new BufferedWriter(fw);
rowCount = c.getCount();
colCount = c.getColumnCount();
if (rowCount > 0) {
c.moveToFirst();
for (i = 0; i < rowCount; i++) {
c.moveToPosition(i);
for (j = 0; j < colCount; j++) {
if (j != colCount - 1)
bw.write(c.getString(j) + ",");
else
bw.write(c.getString(j));
}
bw.newLine();
}
bw.flush();
}
} catch (Exception ex) {
Log.d("Exception","at export topic");
helperr.close();
ex.printStackTrace();
}
helperr.close();
c.close();
}
I am calling the function from here:
private View.OnClickListener clickHandler = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.exportToDropBtn) {
try {
exportTopic();
}catch (Exception e){
Log.d("Exception","at export button");
e.printStackTrace();
}
}
Add code to create a file if it does not exist:
File dir = new File(Environment.getExternalStorageDirectory() + "/yourAppName");
// make them in case they're not there
dir.mkdirs();
File wbfile = new File(dir, fileName);
try {
if (!wbfile.exists()) {
wbfile.createNewFile();
}
// BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(
new FileWriter(wbfile, true));
buf.append(strBuilder.toString());
buf.newLine();
buf.close();
} catch(Exception e){
e.printStackTrace();
}

why file is not deleted inspite of using delete function?

for (int i = 0; i < listOfTempFiles.length; i++) {
for (int j = 0; j < listOfFAQFiles.length; j++) {
if (listOfTempFiles[i].isFile() && listOfTempFiles[i].length() > 0) {
if (listOfTempFiles[i].getName().toLowerCase().contains(".pdf")) {
if (listOfTempFiles[i].getName().substring(listOfTempFiles[i].getName().lastIndexOf("#") + 1).equals(listOfFAQFiles[j].getName())) {
try {
List<InputStream> list = new ArrayList<InputStream>();
list.add(new FileInputStream(listOfTempFiles[i]));
list.add(new FileInputStream(listOfFAQFiles[j]));
System.out.println(listOfTempFiles[i].getName() + "with FAQ: " + listOfFAQFiles[j].getName());
int iend = listOfTempFiles[i].getName().lastIndexOf("#");
if (iend != -1) {
outputFilename = listOfTempFiles[i].getName().substring(0, iend);
}
OutputStream out = new FileOutputStream(new File(finalPDFParh + "/" + outputFilename + ".pdf"));
doMerge(list, out);
boolean flag=listOfTempFiles[i].delete();
System.out.println("Flag----->"+flag);
list.clear();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void doMerge(List<InputStream> list, OutputStream outputStream)
throws DocumentException, IOException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
for (InputStream in : list) {
PdfReader reader = new PdfReader(in);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
document.newPage();
//import the page from source pdf
PdfImportedPage page = writer.getImportedPage(reader, i);
//add the page to the destination pdf
cb.addTemplate(page, 0, 0);
}
}
outputStream.flush();
document.close();
outputStream.close();
}
I want to delete original file from listofTempFiles after it merges with FAQ file.doMerge methhod merges pdf added in the list.I have used delete function but it is not deleted?What can I do with it? I have used delete function.

Some of my Users can not download the zip?

hello so I have been writing an updater for my game.
1) It checks a .version file on drop box and compares it to the local .version file.
2) If there is any link missing from the local version of the file, it downloads the required link one by one.
The issue I am having is some of the users can download the zips and some cannot.
One of my users who was having the issue was using windows xp. So some of them have old computers.
I was wondering if anyone could help me to get an idea on what could be causing this.
This is the main method that is ran
public void UpdateStart() {
System.out.println("Starting Updater..");
if(new File(cache_dir).exists() == false) {
System.out.print("Creating cache dir.. ");
while(new File(cache_dir).mkdir() == false);
System.out.println("Done");
}
try {
version_live = new Version(new URL(version_file_live));
} catch(MalformedURLException e) {
e.printStackTrace();
}
version_local = new Version(new File(version_file_local));
Version updates = version_live.differences(version_local);
System.out.println("Updated");
int i = 1;
try {
byte[] b = null, data = null;
FileOutputStream fos = null;
BufferedWriter bw = null;
for(String s : updates.files) {
if(s.equals(""))
continue;
System.out.println("Reading file "+s);
text = "Downloading file "+ i + " of "+updates.files.size();
b = readFile(new URL(s));
progress_a = 0;
progress_b = b.length;
text = "Unzipping file "+ i++ +" of "+updates.files.size();
ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(b));
File f = null, parent = null;
ZipEntry entry = null;
int read = 0, entry_read = 0;
long entry_size = 0;
progress_b = 0;
while((entry = zipStream.getNextEntry()) != null)
progress_b += entry.getSize();
zipStream = new ZipInputStream(new ByteArrayInputStream(b));
while((entry = zipStream.getNextEntry()) != null) {
f = new File(cache_dir+entry.getName());
if(entry.isDirectory())
continue;
System.out.println("Making file "+f.toString());
parent = f.getParentFile();
if(parent != null && !parent.exists()) {
System.out.println("Trying to create directory "+parent.getAbsolutePath());
while(parent.mkdirs() == false);
}
entry_read = 0;
entry_size = entry.getSize();
data = new byte[1024];
fos = new FileOutputStream(f);
while(entry_read < entry_size) {
read = zipStream.read(data, 0, (int)Math.min(1024, entry_size-entry_read));
entry_read += read;
progress_a += read;
fos.write(data, 0, read);
}
fos.close();
}
bw = new BufferedWriter(new FileWriter(new File(version_file_local), true));
bw.write(s);
bw.newLine();
bw.close();
}
} catch(Exception e) {
this.e = e;
e.printStackTrace();
return;
}
System.out.println(version_live);
System.out.println(version_local);
System.out.println(updates);
try {
} catch (Exception er) {
er.printStackTrace();
}
}
I have been trying to fix this for the last two days and I am just so stumped at this point
All the best,
Christian

Categories