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();
}
Related
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();
}
}
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
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?
I have a method to store the input of a 2D array in a .txt file. However, even with the true put on the end of FileWriter fw = new FileWriter("CBB.dat");, something that usually allows for appending in past projects, the file still only receives one entry before writing over it with the next entry. How would this be fixed?
public void Save(String[][] EntryList)
{
try
{
File file = new File("CBB.dat");
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
if (EntryList[0][0] != null)
{
DataOutputStream outstream;
outstream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
for (int row = 0; row < EntryList.length; row++)
{
for (int col = 0; col < EntryList[row].length; col++)
{
if (EntryList[row][col] != null) outstream.writeUTF(EntryList[row][col]);
}
outstream.close();
}
}
else System.out.print("Something is wrong");
} catch (IOException e)
{
e.printStackTrace();
}
}
Use a CharSequence instead of a String[][] (or you could also use variable arity parameters):
public static void save(CharSequence entryList)
{
BufferedReader read;
BufferedWriter write;
File file = new File("CBB.dat");
if (!file.exists())
{
try
{
file.createNewFile();
} catch (Exception e)
{
e.printStackTrace();
}
}
try
{
read = new BufferedReader(new FileReader(file));
String complete = "";
String line = null;
while ((line = read.readLine()) != null)
{
complete += line + "\n";
}
read.close();
write = new BufferedWriter(new FileWriter(file));
write.append(complete);
write.append(entryList);
write.flush();
write.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
This method should write random chars, but it doesn't write anything at all. I'm probably doing something stupidly wrong here, but for the life of me I can't find it.
public void writeRandomChunk(String fileName) {
try {
File saveFile = new File(folderName + '/' + fileName);
PrintWriter writer = new PrintWriter(
new BufferedWriter(
new FileWriter(saveFile)));
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < chunkSize; i++) {
for (int j = 0; j < chunkSize; j++) {
writer.print((char)(r.nextInt(26) + 'a'));
}
writer.println();
}
} catch (Exception e) {
System.out.println("Error in WorldFile writeRandomFile:\n"
+ e.getLocalizedMessage());
}
}
As with any stream (and this applies to most any language), you need to close it when you are done.
Streams are optimized to be fast, and as a consequence, not all of the data you write to them instantly appears in the file. When you close() or flush() a stream, the data is written to the file (or whatever other storage mechanism you are using).
In your case, try the following, instead.
public void writeRandomChunk(String fileName) {
PrintWriter writer = null;
try {
File saveFile = new File(folderName + '/' + fileName);
writer = new PrintWriter(
new BufferedWriter(
new FileWriter(saveFile)));
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < chunkSize; i++) {
for (int j = 0; j < chunkSize; j++) {
writer.print((char)(r.nextInt(26) + 'a'));
}
writer.println();
}
} catch (Exception e) {
System.out.println("Error in WorldFile writeRandomFile:\n"
+ e.getLocalizedMessage());
} finally {
if (writer != null)
writer.close();
}
}
You need to flush() and/or close() the file at some point.
Haven't closed the writer try it in finally.
finally {
writer.close();
}
you should always close your stream. try this pattern with writers:
PrinterWriter writer = null;
try {
writer = new PrinterWriter(...);
// do your write loop here.
} catch (Exception e) {
// recover from exception.
} finally {
if (writer != null) {
writer.close();
}
}