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.
Related
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();
I am trying to read a variable number of lines from a file, hopefully using InputStream object. What I'm trying to do (in a very general sense) is as follows:
Pass in long maxLines to function
Open InputStream and OutputStream for reading/writing
WHILE (not at the end of read file AND linesWritten < maxLines)
write to file
I know InputStream goes on bytes, not lines, so I'm not sure if that's a good API to use for this. If anyone has any reccomendations on what to look at in terms of a solution (other API's, different algorithm) that's be very helpful.
You can have something like this
BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
while (br.readLine() != null && linesWritten < maxLines) {
//Your logic goes here
}
Have a look at these:
Buffered Reader and
Buffered Writer
//Read file into String allText
InputSream fis = new FileInputStream("filein.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line, allText = "";
try {
while ((line = br.readLine()) != null) {
allText += (line + System.getProperty("line.separator")); //Track where new lines should be for output
}
} catch(IOException e) {} //Catch any errors
br.close(); //Close reader
//Write allText to new file
BufferedWriter bw = new BufferedWriter(new FileWriter("fileout.txt"));
try {
bw.write(allText);
} catch(IOException e) {} //Catch any errors
bw.close(); //Close writer
public static void main(String[] args) {
ArrayList<String> studentTokens = new ArrayList<String>();
ArrayList<String> studentIds = new ArrayList<String>();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(new File("file1.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF8"));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
if ((strLine.length()!=0) && (!strLine.contains("#"))) {
String[] students = strLine.split("\\s+");
studentTokens.add(students[TOKEN_COLUMN]);
studentIds.add(students[STUDENT_ID_COLUMN]);
}
}
for (int i=0; i<studentIds.size();i++) {
File file = new File("query.txt"); // The path of the textfile that will be converted to csv for upload
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String newtext = oldtext.replace("sanid", studentIds.get(i)).replace("salabel",studentTokens.get(i)); // Here the name "sanket" will be replaced by the current time stamp
FileWriter writer = new FileWriter("final.txt",true);
writer.write(newtext);
writer.close();
}
fstream.close();
br.close();
System.out.println("Done!!");
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
The above code of mine reads data from a text file and query is a file that has a query in which 2 places "sanid" and "salabel" are replaced by the content of string array and writes another file final . But when i run the code the the final does not have the queries. but while debugging it shows that all the values are replaced properly.
but while debugging it shows that all the values are replaced properly
If the values are found to be replaced when you debugged the code, but they are missing in the file, I would suggest that you flush the output stream. You are closing the FileWriter without calling flush(). The close() method delegates its call to the underlying StreamEncoder which does not flush the stream either.
public void close() throws IOException {
se.close();
}
Try this
writer.flush();
writer.close();
That should do it.
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 !
I want to delete some content of file using java program as below. Is this the write method to replace in the same file or it should be copied to the another file.
But its deleting the all content of the file.
class FileReplace
{
ArrayList<String> lines = new ArrayList<String>();
String line = null;
public void doIt()
{
try
{
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while (line = br.readLine() != null)
{
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
out.write(lines.toString());
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public statc void main(String args[])
{
FileReplace fr = new FileReplace();
fr.doIt();
}
}
I would start with closing reader, and flushing writer:
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
try {
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
The accepted answer is great. However, there is an easier way to replace content in a file using Apache's commons-io library (commons-io-2.4.jar - you can use any latest versions)
private void update() throws IOException{
File file = new File("myPath/myFile.txt");
String fileContext = FileUtils.readFileToString(file);
fileContext = fileContext.replaceAll("_PLACEHOLDER_", "VALUE-TO-BE-REPLACED");
FileUtils.write(file, fileContext);
}
Note: Thrown IOException needs to be caught and handled by the application accordingly.
Read + write to the same file simulatenously is not ok.
EDIT: to rephrase and be more correct and specific - reading and writing to the same file, in the same thread, without properly closing the reader (and flusing the writer) is not ok.
Make sure to:
close any stream when you no longer need them
In particular before reopening it for writing.
truncate the file, to make sure it shrinks if you write less than it had.
then write the output
write individual lines, don't rely on toString.
flush and close when you are finished writing!
If you use buffered IO, you always have to ensure that the buffer is flushed at the end, or you might lose data!
I can see three problems.
First you are writing to out which I assume is System.out, not an output stream to the file.
Second, if you do write to an output stream to the file, you need to close it.
Third, the toString() method on an ArrayList isn't going to write the file like you are expecting. Loop over the list and write each String one at a time. Ask yourself whether you need to write newline characters as well.
The accepted answer is slightly wrong. Here's the correct code.
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
try {
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
}
out.close();
catch (Exception ex) {
ex.printStackTrace();
}
}