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

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.

Related

Appending to text file in android

I am trying to append to a text file that starts off empty and every time the method addStudent() is called it would add a student.toString() line to the said file. I don't seem to get any exceptions but for some reason, after the method call, the file remains empty. Here is my code.
public void addStudent() {
Student student = new Student();
EditText fName = findViewById(R.id.first_name);
EditText lName = findViewById(R.id.last_name);
EditText studentGpa = findViewById(R.id.gpa);
String firstName = String.valueOf(fName.getText());
String lastName = String.valueOf(lName.getText());
String gpa = String.valueOf(studentGpa.getText());
if(firstName.matches("") || lastName.matches("") || gpa.matches("")) {
Toast.makeText(this, "Please make sure none of the fields are empty", Toast.LENGTH_SHORT).show();
} else {
double gpaValue = Double.parseDouble(gpa);
student.setFirstName(firstName);
student.setLastName(lastName);
student.setGpa(gpaValue);
try {
FileOutputStream fos = openFileOutput("students.txt", MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(student.toString());
osw.flush();
osw.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What might be the problem here? The file students.txt itself is located in assets folder
The problem may be with the fact that 'assets' directory doesnt exists on phone. So if I understand you correctly you may checking the wrong file.
What might be the problem here? The file students.txt itself is located in assets folder.
If it is in the assets folder then you should use AssetsManager top open an input stream to it. Files in the assets folder are readonly so trying to write to them does not make sense.
FileOutputStream fos = openFileOutput("students.txt", MODE_APPEND);
That wil create a file in private internal memory of your app. The code looks ok. But it makes no sense trying to find the file on your phone with a file manager or other app as as said that is private internal memory of your app only.
You use a relative path with "studends.txt" and now you do not know where the file resides.
Well the file resides in the path indicated by getFilesDir().
You could as well have used a full path with
File file = new File(getFilesDir(), "students.txt");
and then open a FileOutputStream with
FileOutputStream fos = new FileOutputStream(file);

Created HTML file isn't recognized by my device

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");

PDF Box - Unable to renameTo or Delete files

I'm fairly new to programming and I've been trying to use PDFBox for a personal project that I have. I'm basically trying to verify if the PDF has specific keywords in it, if YES I want to transfer the file to a "approved" folder.
I know the code below is poor written, but I'm not able to transfer nor delete the file correctly:
try (Stream<Path> filePathStream = Files.walk(Paths.get("C://pdfbox_teste"))) {
filePathStream.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
String arquivo = filePath.toString();
File file = new File(arquivo);
try {
// Loading an existing document
PDDocument document = PDDocument.load(file);
// Instantiate PDFTextStripper class
PDFTextStripper pdfStripper = new PDFTextStripper();
String text = pdfStripper.getText(document);
String[] words = text.split("\\.|,|\\s");
for (String word : words) {
// System.out.println(word);
if (word.equals("Revisão") || word.equals("Desenvolvimento")) {
// System.out.println(word);
if(file.renameTo(new File("C://pdfbox_teste//Aprovados//" + file.getName()))){
document.close();
System.out.println("Arquivo transferido corretamente");
file.delete();
};
}
}
System.out.println("Fim do documento: " + arquivo);
System.out.println("----------------------------");
document.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
I wanted to have the files transferred into the new folder. Instead, sometimes they only get deleted and sometimes nothing happens. I imagine the error is probably on the foreach, but I can't seem to find a way to fix it.
You try to rename the file while it is still open, and only close it afterwards:
// your code, does not work
if(file.renameTo(new File("C://pdfbox_teste//Aprovados//" + file.getName()))){
document.close();
System.out.println("Arquivo transferido corretamente");
file.delete();
};
Try to close the document first, so the file is no longer accessed by your process, and then it should be possible to rename it:
// fixed code:
document.close();
if(file.renameTo(new File("C://pdfbox_teste//Aprovados//" + file.getName()))){
System.out.println("Arquivo transferido corretamente");
};
And as Mahesh K pointed out, you don't have to delete the (original) file after you renamed it. Rename does not make a duplicate where the original file would need to be deleted, it just renames it.
After calling renameTo, you shouldn't be using delete.. as per my understanding renameTo works like move command. Pls see this

Cache creating internet shortcuts on windows

First of all, i found some answers about my problem but did not help.
Here's one: Does Windows cache the contents of .url (Internet Shortcut) files?
I have an application that remove the actual shortcuts and create new ones:
for (String shortcut : shortcuts) {
File f = new File(shortcut + ".url");
if (f.exists()) {
f.delete();
}
try {
FileWriter fw = new FileWriter(shortcut + ".url");
fw.write("[InternetShortcut]\n");
fw.write("URL=http://localhost:" + port + "/" + shortcut + "\n");
fw.flush();
fw.close();
} catch (IOException e) {
}
}
This is the result:
[InternetShortcut]
URL=http://localhost:8889/app
And it's fine, but when i change the port and create another shortcut, windows keeps opening the old url.
In the file properties i can see the right url in the details tab, but in the document of web tab still showing the old url.
As default i'm using Chrome, when i drag the .url file to the browser it work and load the right url, but if i double click loads the old url.
Thanks.

Java file.exists() Errors

I am currently working on a "Notepad - type" file for my Object-Oriented Java class. I've got most of the program done - however I am stuck on the following issue:
When the program tries to save a file, it is supposed to first check for a files existence, obviously if the file exists the program will prompt the user for permission to overwrite the existing copy of the file [The overwrite prompt is not written yet, but it will go in the if(selectedFile.exists() == true) portion of code] - and if the file does not exist, the program will create it.
The issue I am having is that the program always creates the file before checking for the files existence. I have looked at probably 20-30+ answers to similar questions - mainly on stackoverflow, and have yet to come across the answer i need. I'm not sure if I am just "not getting it", or if I have really done something wrong..
Any answer - or hint as to where to find the answer - to this issue would be greatly appreciated.
Thank You.
Complete code (for the save portion of the program is shown below).
else if(source == saveFile)//-------------------------//SAVE FILE//--------------------------
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
fileChooser.setDialogTitle("JavaPad - Save File");
int result = fileChooser.showSaveDialog(fileChooser);
String myFile;
try
{
if(result == JFileChooser.APPROVE_OPTION)
{
myFile = fileChooser.getSelectedFile().getName();
File selectedFile = new File(myFile);
String[] lines = textArea.getText().split(System.getProperty("line.separator"));
readToSave = new Scanner(lines.toString()); // CANNOT use toString() on an Array - THIS WILL BE CHANGED PROPERLY?
PrintWriter savePWriter = new PrintWriter(selectedFile);
if(selectedFile.exists() == true)
{
JOptionPane.showMessageDialog(null, "This file already exists.");
statusLabel.setText("File Save Aborted...");
}
else
{
System.out.println("Creating File: " + myFile);
File newFile = new File(fileChooser.getSelectedFile().getName());
savePWriter = new PrintWriter(newFile);
int i = 0;
while(i < lines.length)
{
savePWriter.append(lines[i] + "\n");
System.out.println("Lines appended = " + i);
i++;
}
savePWriter.flush();
savePWriter.close();
statusLabel.setText("File Saved.");
}
}
else
{
JOptionPane.showMessageDialog(null, "Save has been canceled.");
}
}
catch(IOException IOSaveError)
{
System.out.println(IOSaveError);
}
}
You are calling new PrintWriter(selectedFile), which creates the file, right before you check whether selectedFile exists.
Don't create the PrintWriter before checking if the file exists. The PrintWriter is what causes the file to be written to.
You do:
myFile = fileChooser.getSelectedFile().getName();
File selectedFile = new File(myFile);
PrintWriter savePWriter = new PrintWriter(selectedFile); // Creates File! Probably unwanted.
if(selectedFile.exists() == true) // always true because of the line above
By the way, your code is far too complicated. Instead of having the variables selectedFile and newFile, which both are newly created File objects, you could simply use the File object returned by the dialog: newFile = fileChooser.getSelectedFile().
if(selectedFile.exists() == true)
can be simplified to
if (selectedFile.exists())
I recommend to do I/O using try-with-resources whenever possible:
try (final PrintWriter writer = new PrintWriter(selectedFile)) {
// Use writer
}
This helps with accidentally forgetting to close streams.

Categories

Resources