Created HTML file isn't recognized by my device - java

I create a test html file on an Android (7.0) device from string content. File is created fine, shows up with right extension and icon, but format isn't recognized when tapped, giving message "file format is not supported". Yet, if I save this same file to PC and transfer back to device, the issue disappears. It then shows app choices to open html, as it should be.
Tried several write methods. In all cases file was created and content looked right, but format wasn't recognized rightaway. Can't figure out why, is there an extra step or written data required for this? The latest one was with BufferedWriter (to ensure UTF-8) as below:
final File file = new File(path, name + file_extension);
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("test");
strBuilder.insert(0, "<html>"+"\r\n"+"<body><p>"+"\r\n");
strBuilder.insert(strBuilder.length(), "\r\n"+"</p></body>"+"\r\n"+ "</html>");
String html_content=strBuilder.toString();
try
{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
bw.write(html_content);
bw.close();
} catch (IOException e)
{
e.printStackTrace();
Log.e("Exception", "File write failed: " + e.toString());
}

Try to add this before your HTML Tags:
<!DOCTYPE html>
and delete the StringBuilder.append("test");

Related

System.getProperty("line.separator") not working - Android Studio

Currently I have a code where I retrieve the website plain text and store it inside a text file. I managed to do that but when I want to enter a new line in the text file it doesn't work.
My result
This is the article titleThis is the starting of the first paragraph
What I want
This is the article title
This the starting of the first paragraph
My source code
public void storeHTML(Context context, ArrayList<String> storeHTML, String address) {
try {
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/voicethenews");
if (!root.exists()) {
root.mkdirs();
}
address = address.substring(address.lastIndexOf("/") + 1);
File gpxfile = new File(root, address + ".txt");
FileWriter writer = new FileWriter(gpxfile);
//FileOutputStream fileOutputStream = new FileOutputStream(gpxfile);
//BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
for(int i = 0; i < storeHTML.size(); i++) {
//bufferedWriter.write(storeHTML.get(i));
//bufferedWriter.newLine();
writer.append(storeHTML.get(i) + System.lineSeparator());
}
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
I've tried multiple code and solution but it's still not working.
I found the actual reason why it doesn't display as I intended.
The reason why it doesn't seem to work in the first place it was due to me opening the text file using the default notepad. When open using other text editor such as notepad++, the output in the text file was writen as intended.
If you get detail from HTML. So, let use <br>, instead of <br \>
This is an example code to add text to a textView b
b.setText(Html.fromHtml("<b>" + st + "</b>" + "<br/>" + cursor.getString(1)));
Reference: How do i add a new line in html format in android?
This question is probably addressing the exact same issue you are having:
System.lineSeparator() doesn't exist in android
There was a bug in the pre 1.7 SDKs where you would have to call the environmental variable directly.

Load Html file with UTF8 encoding from assets into a TextView

I have HTML file in assets folder which is encoded in UTF8(contain Persian characters), I want to read this file and load it into a TextView.I read lots of posts like load utf-8 text file , load HTML file into TextView , read UTF8 text file from res/raw and write this code:
try{
InputStream inputStream = getResources().getAssets().open("htmls/salamati.html");
// I also try "UTF-8" but none of them worked
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream,"UTF8"));
StringBuilder total = new StringBuilder();
String html;
while ((html = r.readLine()) != null) {
total.append(html);
}
// total contains incorrect characters
textView.setText(Html.fromHtml(total.toString()));
}
catch (IOException exception)
{
textView.setText("Failed loading HTML.");
}
But It show incorrect characters!
I also try to convert total.toString() into a UTF8 String array and then add it to textView but it didn't work too
textView.setText(Html.fromHtml(new String(total.toString().getBytes("ISO-8859-1"), "UTF-8")));
There is no problem with textView or emulator because when I load HTML from Database, It shows utf8 characters correctly!
So what should I do?
After lots of searching and test some other codes,at the end I replace my HTML file with another one.Surprisingly my code works fine! I investigate former HTML file and notice that it has Unicode encoding!!!
So if you have a same problem, first of all check your file's encoding and make sure that it is correct.

Copy file from Android to Windows

I wrote a small app, which creats a XML file on my Android device. No I try to copy it from my phone to my Windows PC. In Windows Explorer I can't see this file specific file, on my phone I can see this file with various file explorers. When I reboot my phone, the file appears in Windows Explorer, but I can't copy it to my desktop.
Here is my code which creates my file:
String filename = "myfile.xml";
String dir = Environment.getExternalStorageDirectory().getPath()+"/"+c.getResources().getString(R.string.app_name);
createDir(dir);
File file = new File(dir,filename);
FileWriter out=null;
try {
String xml = createXml();
try {
out = new FileWriter(file);
out.write(xml);
out.close();
} catch (Exception e) {
out.close();
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
My guess is, this code doesn't free the file handle so Androids MTP cannot access this file. This would also explain, why the file is shown and could be deleted (but not able to be transfered to my PC) after rebooting my phone.
Any suggestions what goes wrong?
I think you should refresh the media scanner for that file
sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageAdded))
);

How to use a save file dialog from a servlet?

I am trying to let the user save data from my servlet as a CSV file. Originally I was just locating their desktop to drop the file, but permission would be denied with this route so I want to ask the user where they want to save it.
From what I am seeing, I cannot use the Swing API in a servlet because Tomcat does not know how to draw the GUI. I tried this code:
String fileName = "ClassMonitor" + formatter.format(currentDate) + ".csv";
File csvFile = new File(fileName);
//Attempt to write as a CSV file
try{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setSelectedFile(csvFile);
int returnValue = fileChooser.showSaveDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION)
{
BufferedWriter out = new BufferedWriter(new FileWriter(csvFile));
//Iterates and writes to file
for(ClassInfo classes : csvWrite)
{
//Check if the class has a comma. Currently, only section titles have a comma in them, so that's all we check for.
classes.setSectionTitle(replaceComma(classes.getSectionTitle()));
out.write(classes.toString());
}
//Close the connection
out.close();
}
//Log the process as successful.
logger.info("File was successfully written as a CSV file to the desktop at " + new Date() + "\nFilename" +
"stored as " + fileName + ".");
}
catch(FileNotFoundException ex)
{
//Note the exception
logger.error("ERROR: I/O exception has occurred when an attempt was made to write results as a CSV file at " + new Date());
}
catch(IOException ex)
{
//Note the exception
logger.error("ERROR: Permission was denied to desktop. FileNotFoundException thrown.");
}
catch(Exception ex)
{
//Note the exception
logger.error("ERROR: Save file was not successfull. Ex: " + ex.getMessage());
}
}
But this will throw a headlessException.
Any guidance on how to implement something like a save file dialog in a servlet would be appreciated.
Just write it to the response body instead of to the local(!!) disk file system.
response.setContentType("text/csv"); // Tell browser what content type the response body represents, so that it can associate it with e.g. MS Excel, if necessary.
response.setHeader("Content-Disposition", "attachment; filename=name.csv"); // Force "Save As" dialogue.
response.getWriter().write(csvAsString); // Write CSV file to response. This will be saved in the location specified by the user.
The Content-Disposition: attachment header takes care of the Save As magic.
See also:
JSP generating Excel spreadsheet (XLS) to download
You can't call the JFileChooser from the servlet because the servlet runs on the server, not on the client; all of your Java code is executed on the server. If you want to save the file on the server, you need to already know the path you want to write to.
If you want to prompt the user's browser to save the file, use the content-disposition header: Uses of content-disposition in an HTTP response header

File Delete and Rename in Java

I have the following Java code which will search in an xml for a specific tag and then will add some text to it and save that file. I couldnt find a way to rename the emporary file to the original file. Please suggest.
import java.io.*;
class ModifyXML {
public void readMyFile(String inputLine) throws Exception
{
String record = "";
File outFile = new File("tempFile.tmp");
FileInputStream fis = new FileInputStream("InfectiousDisease.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);
while ( (record=br.readLine()) != null )
{
if(record.endsWith("<add-info>"))
{
out.println(" "+"<add-info>");
out.println(" "+inputLine);
}
else
{
out.println(record);
}
}
out.flush();
out.close();
br.close();
//Also we need to delete the original file
//outFile.renameTo(InfectiousDisease.xml);//Not working
}
public static void main (String[] args) {
try
{
ModifyXML f = new ModifyXML();
f.readMyFile("This is infectious disease data");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Thanks
First delete the original file and then rename the new file:
File inputFile = new File("InfectiousDisease.xml");
File outFile = new File("tempFile.tmp");
if(inputFile.delete()){
outFile.renameTo(inputFile);
}
A good method to rename files is.
File file = new File("path-here");
file.renameTo(new File("new path here"));
In your code there are several issues.
First your description mentions renameing the original file and adding some text to it. Your code doesn't do that, it opens two files, one for reading and one for writing (with the additional text). That is the right way to do things, as adding text in-place is not really feasible using the techniques you are using.
The second issue is that you are opening a temporary file. Temporary files remove themselves upon closing, so all the work you did adding your text disappears as soon as you close the file.
The third issue is that you are modifying XML files as plain text. This sometimes works as XML files are a subset of plain text files, but there is no indication that you attempted to ensure that the output file was an XML file. Perhaps you know more about your input files than is mentioned, but if you want this to work correctly for 100% of the input cases, you probably want to create a SAX writer that writes out all a SAX reader reads, with the additional information in the correct tag location.
You can use
outFile.renameTo(new File(newFileName));
You have to ensure these files are not open at the time.

Categories

Resources