save string list to a file since you compare it - java

I am saving to a file a double list (mydata) which is some data the user enters and a string list (dates_Strings) which is the current date.
The user enters some data and pressing a 'save' button , I save the data and the currents date.
So , user may enter "1" and press save (1, 08/05/13)
enter "2" and press save (2, 08/05/13).
Because the user may enter data during a day (same date) I don't want to save many instances of the date.I want to save all the user data in that date.
I tried sth like:
for (int i=1;i<mydata.size();i++){
bw.write(mydata.get(i)+",");
while (!(dates_Strings.get(i).equals(dates_Strings.get(i-1))))
bw.write(dates_Strings.get(i)+"\n");
}
but it saves only the last entered data.
I am saving as:
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
directory.mkdirs();
File file = new File(directory, filename);
FileOutputStream fos;
//saving them
try {
fos = new FileOutputStream(file,true); //true in order to append
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i=1;i<mydata.size();i++){
//if (!(dates_Strings.get(i).equals(dates_Strings.get(i-1))))
bw.write(mydata.get(i)+","+dates_Strings.get(i)+"\n");
}
value.setText("");
bw.flush();
bw.close();
} catch (IOException e2) {
e2.printStackTrace();
}//catch
}
I am loading as:
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
File file = new File(directory, filename);
String s;
FileInputStream fis;
try {
fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
do {
s = br.readLine();
if (s != null ){
String[] splitLine = s.split(",");
mydata.add(Double.parseDouble(splitLine[0]));
//dates_Strings.add(thedate.parse(splitLine[1]));
dates_Strings.add(splitLine[1]);
}
} while (s != null );
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Mmmm... maybe this can help you, basic idea as mentioned by our colleagues: receive input, save it in file, receive new input, read the existing file before, add the new content to the old content and save the updated content of your file.
//Asumming your values are these:
List<String> datesList = new ArrayList<String>();
List<Double> dataList = new ArrayList<Double>();
//You must fill your data of course...
//I use a buffer to put in order my data
StringBuffer stringAppender = new StringBuffer();
for (int i = 0; i < dataList.size(); i++) {
stringAppender.append(dataList.get(i));
stringAppender.append(",");
stringAppender.append(datesList.get(i));
if (i != dataList.size()-1) {
stringAppender.append("\n");
}
}
//I use the Buffered Writer and then save all the data ordered in one single String.
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/home/mtataje/saved.txt")));
bw.write(stringAppender.toString());
bw.close();
Then... you have new inputs right?
//I read my file first
BufferedReader br = new BufferedReader(new FileReader(new File("/home/mtataje/saved.txt")));
String line;
StringBuffer auxBuffer = new StringBuffer();
while ((line = br.readLine()) != null) {
auxBuffer.append(line);
auxBuffer.append("\n");
}
//Then append to the StringBuffer again, but your StringBuffer has data saved inside :)
for (int i = 0; i < newDataListIncoming.size(); i++) {
auxBuffer.append(newDataListIncoming.get(i));
auxBuffer.append(",");
auxBuffer.append(newDatesIncoming.get(i));
if (i != newDataListIncoming.size()-1) {
auxBuffer.append("\n");
}
}
//And write your file
BufferedWriter bw2 = new BufferedWriter(new FileWriter(new File("/home/mtataje/saved.txt")));
bw2.write(auxBuffer.toString());
bw2.close();
Of course, you will use methods and not use redundancy in your code as me, I hope I gave you a hand with this. Best regards.

You must load the previous value in your file .. read it and add new value .. then save it !

Related

Why won't my lambda write to the .txt files it creates?

I have an AWS lambda program written in Java that is supposed to create a bunch of txt files then write URLs to them and move them to a bucket. It appears to be creating the .txt files in the /tmp/ folder of the lambda but not writing anything to them, because I keep getting FL2: null. The bucket gets .txt files with the right names but they're empty.
The FileNames are all of the format "/tmp/[name].txt". The map has txt filenames followed by a list of URLs. The buffered reader was simply my own code to see if it could read the .txts that were created.
for (Map.Entry<String, ArrayList<String>> entry: files.entrySet()) {
String fileName = entry.getKey();
ArrayList<String> list = entry.getValue();
File file = new File(fileName);
FileWriter writer = null;
BufferedWriter bw = null;
BufferedReader br = null;
try {
if (!file.exists()){
log.info("It doesn't exist as a temp.");
if( !file.createNewFile()){
log.error(fileName+" not created. Skipping");
continue;
}
}
writer = new FileWriter(file, StandardCharsets.UTF_8);
bw = new BufferedWriter(writer);
for (int i=0; i< list.size(); i++) {
String url = list.get(i);
log.info("Inserting " + url + " into file " + fileName);
if (i !=0){
bw.write("\n");
}
bw.write(url);
}
br = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8));
log.info("FL2: "+br.readLine());
String key = fileName.substring(5);
amazonS3.putObject("[bucketname]", key, file);
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
if (writer != null) {
writer.close();
}
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.info("End of the sitemap generator");
}
I tried the above code, and I tried printWriter turning into a bufferedWriter.
Your code is writing to the text file and later reading from the same text file. But ... your code doesn't close the writer until the finally section of code so the read happens before the writer closes and consequently the written data, which is buffered, has not been flushed to disk.
The fix is to close the buffered writer before reading from the same file.
Also, you can reduce the amount of state in your program as follows, while also reducing the number of closes you have to do:
BufferedWriter bw = new BufferedWriter(new FileWriter(file, ...));
You might also consider using try-with-resources to auto flush/close your files.

How can i remove a particular text from a file in java?

I have tried to implement a simple program to delete a particular text from a file, some how it is not able to delete it. I am reading entire file content into a temp file , delete the user input string from it and update the content to the original file.
Any help would be highly appreciated.
public class TextEraser{
public static void main(String[] args) throws IOException {
System.out.print("Enter a string to remove : ");
Scanner scanner = new Scanner(System. in);
String inputString = scanner. nextLine();
// Locate the file
File file = new File("/Users/lobsang/documents/input.txt");
//create temporary file
File temp = File.createTempFile("file", ".txt", file.getParentFile());
String charset = "UTF-8";
try {
// Create a buffered reader
// to read each line from a file.
BufferedReader in = new BufferedReader(new FileReader(file));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
String s = in.readLine();
// Read each line from the file and echo it to the screen.
while (s !=null) {
s=s.replace(inputString,"");
s = in.readLine();
}
writer.println(s);
// Close the buffered reader
in.close();
writer.close();
file.delete();
temp.renameTo(file);
} catch (FileNotFoundException e1) {
// If this file does not exist
System.err.println("File not found: " + file);
}
}
After replace with input string, write string immediate in file.
while (s != null) {
s = s.replace(inputString, "");
writer.write(s);
// writer.newLine();
s = in.readLine();
}
For new line , use BufferedWriter in place of PrintWriter, it contains method newLine()
writer.newLine();
Remove this
writer.println(s);

java android - can't download whole page html code

im trying to download a source code of a page with this code:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
URL url;
InputStream is = null;
BufferedReader br;
String line;
List<String> list = new ArrayList<>();
try {
url = new URL("https://csgostash.com/weapon/MAG-7");
is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null)
list.add(line);
File f = new File("/data/data/abc.def.asd/cache/nwm.txt");
FileWriter fw = new FileWriter(f, true);
for(String x : list)
fw.append(x +"\n");
} catch (IOException e) {
e.printStackTrace();
}
but that doesnt download a whole code. it ends few lines before it should (i know it because, how u can see, i wrote whole content of the list to a text file). do u know any others methods to save whole website code to an array/list?
There may not be a problem, you must close or flush a FileWriter when done:
FileWriter fw = new FileWriter(f, true);
for(String x : list)
fw.append(x +"\n");
fw.close();
Or use try-with-resources if you have min sdk >= 19:
try (FileWriter fw = new FileWriter(f, true)) {
for(String x : list)
fw.append(x +"\n");
}
Otherwise you could see a partially written file.

Editing a text file in java

I want add few strings to a text file in a particular location.
I have used BufferedReader to read the text file. Then I added the string at the particular position and wrote the modified text to a new temp file using BufferedWriter.
Then I deleted the old file and renamed the temp file to old file name.
This works sometimes and does not work sometimes. The delete() function sometimes does not delete the file. I have closed all the BufferedWriter's, but the problem still occurs sometimes.
Code:
public boolean cart(String uname, String item) throws IOException {
File file = new File("C:\\$$$$.tmp");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
File fileop = new File("C:\\value.text");
FileReader fr = new FileReader(fileop.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null) {
String val[] = line.split(",");
if (val[0].equals(uname)) {
String linenew = line + item + "&";
bw.append(linenew);
bw.newLine();
bw.flush();
} else {
bw.append(line);
bw.newLine();
bw.flush();
}
}
br.close();
bw.close();
fileop.delete();
file.renameTo(fileop);
return true;
}
I found the answer by myself after spending one full day of searching..
Answer is:
It is enough to close the bufferedReader but also the fileReader..
fr.close(); should be inserted after br.close();

How to I read and edit txt in a serialised file?

I have an object which is serialised and written to a file.
Before de serialising the file back into an object instance, I want to maliciously edit the txt in the file.
//FILE TAMPER
//Lexical block: Tamper
{
String output = null;
//Lexical block make output
{
LinkedList<String> lls = new LinkedList<String>();
//Lexical block: Reader
{
BufferedReader br = new BufferedReader(new FileReader(fileString));
while (br.ready()) {
String readLine = br.readLine();
lls.add(readLine);
}
br.close();
}
//Lexical block: manipulate
{
//Henry Crapper
final String[] llsToArray = lls.toArray(new String[lls.size()]);
for (int i = 0; i < llsToArray.length; i++) {
String line = llsToArray[i];
if (line.contains("Henry")) {
line = line.replace("Henry",
"Fsekc");
llsToArray[i] = line;
}
if (line.contains("Crapper")) {
line = line.replace("Crapper",
"Dhdhfie");
llsToArray[i] = line;
}
lls = new LinkedList<String>(Arrays.asList(llsToArray));
}
}
//Lexical block: write output
{
StringBuilder sb = new StringBuilder();
for (String string : lls) {
sb.append(string).append('\n');
}
output = sb.toString();
}
}
//Lexical block: Writer
{
BufferedWriter bw = new BufferedWriter(new FileWriter(fileString));
bw.write(output);
bw.close();
}
}
However the edited file isn't correct and has some unusual characters.
//Before
¨Ìsr&Snippets.Parsed.EmployeeSerialization0I
bankBalanceLnametLjava/lang/String;xp•Åt
Henry Crappe
//After
ÔøΩÔøΩsr&Snippets.Parsed.EmployeeSerialization0I
bankBalanceLnametLjava/lang/String;xpÔøΩÔøΩt
Fsekc Dhdhfie
I'm guessing there is some sort of non readable character issue or something?
Answer continued in a new question is here
A file which contains a serialized object instance is a binary file: you should not edit it with a BufferedWriter. Edit it with a RandomAccessFile, for example.
If you are wondering of why, the charset used in a Writer could not map one-to-one with a byte. Saving all the file would change also unexpected positions.

Categories

Resources