This is the code snippet that I'm executing, it executes until the for loop, but doesn't print out the contents of the loop into the file.
public void createFile(DatabaseHandler dh, String fromStation, String toStation) {
try {
Log.d(TAG,""+fromStation+" "+toStation);
final File dir = new File(Environment.getExternalStorageDirectory() + "/RDPS");
dir.mkdirs();
Log.d(TAG,"directory made!");
File file = new File(dir, "annex_4.txt");
FileOutputStream fos = new FileOutputStream(file);
List<DatabaseEntries> delist = dh.getAllEntries();
int sizeOfList = delist.size();
fos.write(("Initial Data! "+sizeOfList+" \n").getBytes());
fos.write(("LATITUDE \t LONGITUDE ").getBytes());
for(int i = 0; i < sizeOfList; i++)
{
fos.write((i+"\n").getBytes());
DatabaseEntries de = delist.get(i);
String latitude = de.getLatitude();
String longitude = de.getLongitude();
fos.write((latitude + "\t" + longitude + "\t").getBytes());
}
fos.close();
}
catch(Exception e) {
String ee = e.toString();
Log.d("TAG",ee);
}
my file is being created into the correct directory, but the contents of the file are just :-
Initial Data! 105
LATITUDE LONGITUDE
where 105 is an example of the size of the list that I'm getting as an output.
I'm pretty new to android and list-programming, so I can't really get to the root of this problem. Any help is much appreciated. Thanks!
Related
I am trying to write a data from database to a csv file via java thread. For writing i am making use of OPENCSV jar. The problem i am facing is that sometimes in csv file values get corrupted like shown below in line 1 and 4.
I have no idea as to why this is happening. Values coming from the database are all ok (as can be seen in the logs) but in csv file its not.
[E[EcoUnit 01] [Segment B/1] [2017-12-29 22:13:23.047] [ventilation air humidity] [70.18]
[EcoUnit 01] [Segment B/1] [2017-10-25 22:21:36.583] [ventilation air humidity] [69.65]
[EcoUnit 01] [Segment B/1] [2017-10-25 22:22:36.59] [ventilation air humidity] [69.33]
[EcoUnit 01] [Segment B/017-11-14 12:02:48.013] [ventilation fan] [30]
I would be really grateful if anyone can let me suggest why this is happening.
Code is as follows: -
List<String> values = new ArrayList<String>();
fw = new FileWriter(file);
writer = new CSVWriter(fw);
writer.writeNext(headers);
values.add(doc.getFieldValue("Unit_Label").toString());
values.add(doc.getFieldValue("Segment_Label").toString());
values.add("[" + doc.getFieldValue("datestring").toString() + "]");
values.add(doc.getFieldValue("Item_Label").toString());
values.add(doc.getFieldValue("Value").toString());
writer.writeNext(values.toArray(new String[]{}));
Adding complete code of the function responsible for creating file and writing into it.
public void createAndFillFile(String startDateStr, String endDateStr, int fileNumber,SolrDocumentList results){
try{
String startDateParts[] = startDateStr.split(" ");
String startDate = startDateParts[0];
String endDateParts[] = endDateStr.split(" ");
String endDate = endDateParts[0];
if(fileNumber == 1){
Date date = new Date() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss") ;
String currentDate = dateFormat.format(date); //This line can be removed and in below line directly can be used
zipFile = currentDate + ".zip";
dir = new File("C:" + File.separator + "EcotronDownloadable" + File.separator + currentDate);
dir.mkdir();
path = dir.getAbsolutePath() + File.separator ;
file = new File(path+ startDate + "_" + endDate + "_" + fileNumber + ".csv");
fw = new FileWriter(file);
writer = new CSVWriter(fw);
writer.writeNext(headers);
}
synchronized(file){
for (SolrDocument doc : results) {
List<String> values = new ArrayList<String>();
Thread.sleep(1);
long fileLength = file.length();
if(fileLength<maxFileSize){
values.add(doc.getFieldValue("Unit_Label").toString());
values.add(doc.getFieldValue("Segment_Label").toString());
values.add("[" + doc.getFieldValue("datestring").toString() + "]");
values.add(doc.getFieldValue("Item_Label").toString());
values.add(doc.getFieldValue("Value").toString());
//log.trace(values);
writer.writeNext(values.toArray(new String[]{}));
}
else{
fw.flush();
fw.close();
// writer.close();
j = j + 1;
file = new File(path + startDate + "_" + endDate + "_" + j + ".csv") ;
fw = new FileWriter(file);
writer = new CSVWriter(fw);
writer.writeNext(headers);
values.add(doc.getFieldValue("Unit_Label").toString());
values.add(doc.getFieldValue("Segment_Label").toString());
values.add("[" + doc.getFieldValue("datestring").toString() + "]");
values.add(doc.getFieldValue("Item_Label").toString());
values.add(doc.getFieldValue("Value").toString());
//log.trace(values);
writer.writeNext(values.toArray(new String[]{}));
}
}
}
// fw.flush();
// fw.close();
// writer.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
``
You might have two FileWriter instances (in different threads) pointing to the same file and writing at same time.
try this:
synchronized (file)
{
List<String> values = new ArrayList<String>();
fw = new FileWriter(file);
writer = new CSVWriter(fw);
writer.writeNext(headers);
values.add(doc.getFieldValue("Unit_Label").toString());
values.add(doc.getFieldValue("Segment_Label").toString());
values.add("[" + doc.getFieldValue("datestring").toString() + "]");
values.add(doc.getFieldValue("Item_Label").toString());
values.add(doc.getFieldValue("Value").toString());
writer.writeNext(values.toArray(new String[]{}));
}
Hi I have a tricky problem that seems simple but it has been teasing my brain ever since I started it.
My app allows the user to enter a Product Number and an image Number. The app can take more than one image of one product.
When saving the images to gallery I would like to add a sequential file number to it so that I know which images are linked to which product.
Here is the format in which the file will be saved:
String fname = TypeNo + "(" + ImageNo + ")" + sequentialNumber + ".jpg";
For example,
Type No = Test1;
ImageNo = 1;
sequentialNumber = 1;
fname = Test1(1)1;
When the user saves this one, they go back to the data entry activity and If they keep the same TypeNo/ProductCode then the sequentialNo should stay the same for the next save.
If the user enters a different TypeNo/ProductNo then the sequentialNo will increment.
Here is the code I have tried so far which doesn't increment correctly when a new TypeNo is entered:
private void saveImageToExternalStorage(Bitmap bitmap_view) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/Digital_Images");
myDir.mkdirs();
String fname = TypeNo + "(" + ImageNo + ")" + sequentialNumber + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap_view.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor editor = sharedPreferences.edit();
String lastUsedTypeNo = TypeNo;
editor.putString("TypeNo", lastUsedTypeNo);
editor.putInt("sequentialNum", sequentialNumber);
editor.apply();
}
#Override
public void onResume() {
super.onResume();
String TypeNoRetrieved = sharedPreferences.getString("TypeNo", null);
int SQNumRetrieved = sharedPreferences.getInt("sequentialNum", 1);
if (TypeNoRetrieved != null || SQNumRetrieved != 0) {
if (TypeNoRetrieved == lastUsedTypeNo ) {
sequentialNumber = SQNumRetrieved;
} else {
sequentialNumber++;
}
}
}
Anyone able to solve this puzzle for me?
I am trying to save my ArrayList into a text file. But the format of how it is saved is wrong. My code:
ArrayList<Vehicle> vehs = new ArrayList<Vehicle>();
vehs.add(new Vehicle("QJT123", "Starlet 99", 35.0, 190000));
vehs.add(new PremiumVehicle("TUX132", "BWM 05 ", 90.0, 12000, 100, 10000, 5000));
Constructor used for these 2:
public PremiumVehicle(String vehicleID, String description, double dailyRate, int odometer, int allowance, int serLength, int lastOdo) //subclass
public Vehicle(String vehicleID, String description, double dailyRate, int odometer) //Superclass
Both of these are stored into the Vehicle ArrayList. Code to save to text file:
private static void saveFile(ArrayList<Vehicle> vehs){
File fileName = new File("VehicleList.txt");
try {
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
for (int i = 0; i < vehs.size(); i++){
output.write(vehs.get(i).toString() + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "I cannot create that file");
}
}
My output in VehicleList.txt:
vehicle ID = QJT123 Description = Starlet 99 Status = A Daily Rate = 35.0 Odometer reading = 190000vehicle ID = TUX132 Description = BWM 05 Status = A Daily Rate = 90.0 Odometer reading = 12000 Mileage allowance = 100 service length = 10000 Last Service = 5000
How do i make it such that each new line is added when writing in a new ArrayList object, e.g:
vehicle ID = QJT123 Description = Starlet 99 Status = A Daily Rate = 35.0 Odometer reading = 190000
vehicle ID = TUX132 Description = BWM 05 Status = A Daily Rate = 90.0 Odometer reading = 12000 Mileage allowance = 100 service length = 10000 Last Service = 5000
I've tried using vehs.get(i).toString() + "\n" but it doesn't seem to work.
Most likely, your platform does not see \n as a newline character - that thing depends on the OS.
One way to obtain the correct newline marker:
String lineSep = System.getProperty("line.separator");
or even simpler:
String lineSep = System.lineSeparator();
and instead of using + "\n" you do + lineSep in your code.
BufferedWriter has a newLine() method, you may use that if you declare output as a BufferedWriter .
private static void saveFile(ArrayList<Vehicle> vehs){
File fileName = new File("VehicleList.txt");
try {
FileWriter fw = new FileWriter(fileName);
BufferedWriter output = new BufferedWriter(fw);
for (int i = 0; i < vehs.size(); i++){
output.write(vehs.get(i).toString());
output.newLine();
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "I cannot create that file");
}
}
Also for the javadoc of the method :
Writes a line separator. The line separator string is defined by the
system property line.separator, and is not necessarily a single
newline ('\n') character.
I have some Lists consist of some Apk files' informations:
static ContentAndDAO contentAndDao = new ContentAndDAO();
public static void main(String[] args)
{
int manifestNum;
long contentId = 111111;
long devFileId = 222222;
List<DevFile> fileList;
List<DevSupport> supports = null;
List<ContentDev> contentList = new ArrayList<ContentDev>();
ContentDevDAO contentDevDao = new ContentDevDAO();
DevFileDAO devFileDao = new DevFileDAO();
ManifestMethods manifestMethods = new ManifestMethods();
DevFile apkFile = null;
try
{
manifestNum = 1;
File dir = new File("C:\\Users\\lenovo 01\\Desktop\\basari\\buulkcontent\\klasorlenen");
String[] extensions = new String[] {"apk"};
List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
Collections.sort(files);
for(File file : files)
{
apkFile = new DevFile();
fileList = new ArrayList<DevFile>();
if(file.getName().contains(".apk"))
{
FileInputStream fis = new FileInputStream(new File(file.getAbsolutePath()));
String apkMd5 = DigestUtils.md5Hex(fis);
fis.close();
System.out.println(file);
System.out.println(file.length());
System.out.println(apkMd5.toUpperCase());
System.out.println(contentId);
apkFile.setByteSize(file.length());
apkFile.setUrl("/file/getContent/" + contentDevDao.createId(contentId) + "/" + apkMd5.toUpperCase() + "/apk");
apkFile.setThumbnailUrl("/file/getContent/" + contentDevDao.createId(contentId) + "/" + apkMd5.toUpperCase() + "/apk");
apkFile.setDeleteUrl("/file/deleteContent/" + contentDevDao.createId(contentId) + "/" + apkMd5.toUpperCase() + "/apk");
apkFile.setFileHash(apkMd5.toUpperCase());
apkFile.setFilePath("content/" + contentDevDao.createId(contentId) + "/" + apkMd5.toUpperCase() + ".apk");
apkFile.setFileName(manifestMethods.getApplicationName(manifestNum).replaceAll(" ", "-") + ".apk");
apkFile.setName(manifestMethods.getApplicationName(manifestNum).replaceAll(" ", "-"));
apkFile.setPackageVersion(manifestMethods.getVersionName(manifestNum));
apkFile.setPackageName(manifestMethods.getPackageName(manifestNum));
apkFile.setPackageVersionCode(manifestMethods.getVersionCode(manifestNum));
apkFile.setSdkVersion(manifestMethods.getSdkVersion(manifestNum));
contentId++;
devFileId++;
manifestNum++;
}
}
for(int y = 1; y <= 53; y++)
{
manifestNum = 1;
fileList = new ArrayList<DevFile>();
DevFile file = new DevFile();
ContentDev content = new ContentDev();
/* some DevFile file addings */
fileList.add(file);
content.setDevFiles(fileList);
contentList.add(content);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
When I print the information one by one to the console, its showing just as I want. But in the List, its always showing only the last added apk file's package name, byte size, hash number etc. Of course I don't want that. What is wrong?
Note: Please don't mind the lack of legibility and modularity of code. I'm new to the object oriented structure.
You are creating a new list in each iteration of your loop :
for(int y = 1; y <= 53; y++)
{
fileList = new ArrayList<DevFile>();
DevFile file = new DevFile();
ContentDev content = new ContentDev();
/* some DevFile file addings */
fileList.add(file);
...
This means only the last file will be in that list at the end.
Change it to :
fileList = new ArrayList<DevFile>();
for(int y = 1; y <= 53; y++)
{
DevFile file = new DevFile();
ContentDev content = new ContentDev();
/* some DevFile file addings */
fileList.add(file);
...
In addition, I see that you create instances of DevFile in another loop, but never do anything with them. Shouldn't they be added to the List?
I am trying to develop a program that searches for duplicate files using MD5 hash, it will compare two hash files for duplicate.
I am having difficulties comparing the two files, after hashing the files with MD5 hash code, I keep getting the error "Java.IO.FileNotFoundException.". Here is my code, I do not know what I am doing wrong.
////////////////////// It is a GUI Program ////////////////////////
DefaultListModel m = new DefaultListModel(); // List Model for displaying the hash codes
int rval = chooser.showOpenDialog(null); //JFileChooser for selecting files tobehashed
if(rval == JFileChooser.APPROVE_OPTION){
File f = chooser.getCurrentDirectory();
String fs = f + "";
if(!f.isDirectory()){
JOptionPane.showMessageDialog(null, "Supplied Directory does not exist");
}
//display files on the TesxtField component
File[] filenames = f.listFiles();
String fn = Arrays.toString(filenames);
String type = f.isFile() ? "File" : "Directory : ";
long len = f.length();
String all = type +" "+" " + " Length: " + len;
dis.setText(all + "\n");
dis.setText(fn + "\n" + "\n" );
//Loops through the file and check sum of the list files
for(File file : f.listFiles()){
String hash;
try {
hash = MD5.asHex(MD5.getHash(file));
////////// Here is where my problems starts, Please help //////////
for(int i = 0; i < hash.length(); i++ )
for(int j = i + 1; j < hash.length(); j++){
File[] f1 = new File[i];
File[] f2 = new File[j];
boolean check = MD5.hashesEqual(MD5.getHash(new File(Arrays.toString(f1))),MD5.getHash(new File(Arrays.toString(f2)))); //compares the byte of files
System.out.println(check);
m.addElement(hash);
task.setModel(m);
}
}catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
For reading files in Java you need an InputStream object.
Look at this Question Getting a File's MD5 Checksum in Java which seems to help you with your problem