I want my logcat to show entire fetched HTML code not just some part of
it as i'm using regex to dynamically find certain resources.
I have tried to print the fetched HTML into a text file(on PC not on the
android device) but nothing seem to work.
The text file is just for rough work while working with the HTML so that can get the regular expression.
private void writeToFile(String data)
{
try
{
OutputStream outputStream=new FileOutputStream("getNames.txt");
Writer outputStreamWriter=new OutputStreamWriter(outputStream);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch(Exception e)
{
Log.i("EXCEPTION",e.toString());
}
}
can you guys please show how to do file handling properly in android studio.
below should work, for printing log use any mode you would like use, I have shown all in catch block.:
private void writeToFile(String data)
{
try (FileWriter writer = new FileWriter("getNames.txt");
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(data);
}
catch(Exception e)
{
Log.i("EXCEPTION",e.getMessage()); //print in info mode
Log.d("EXCEPTION",e.getMessage()); //print in debug
Log.e("EXCEPTION",e.getMessage()); //print error
}
}
OR create file object where you have permission to write or give permission to writable.change path name of your system.
private void writeToFile(String data)
{
File file = new File("C:\\Users\\user\\OneDrive\\Desktop\\test\\getNames.txt");
file.setWritable(true);
try (FileWriter writer = new FileWriter("getNames.txt");
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(data);
}
catch(Exception e)
{
Log.i("EXCEPTION",e.getMessage()); //print in info mode
Log.d("EXCEPTION",e.getMessage()); //print in debug
Log.e("EXCEPTION",e.getMessage()); //print error
}
}
Related
Im using this code in order to write some text to a file, while limiting the size of the file to 1G
but every time a new text is entered, its overriding the current file content.
How do I disable the overriding and still keeping the file size limit?
public synchronized void writeToAFile(String msg,String filePath) {
Path path = FileSystems.getDefault().getPath(filePath);
final long SIZE_1GB = 1073741824L;
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new LimitedOutputStream(Files.newOutputStream(path), SIZE_1GB), StandardCharsets.UTF_8))) {
writer.append(msg);
} catch (Exception e) {
LOGGER.error("Something went wrong while writing to the file {} ", e.getMessage());
e.printStackTrace();
}
}
You should create appendable stream when defining Files.newOutputStream(path).
So providing StandardOpenOption.APPEND option will be fix your problem
// append to an existing file, fail if the file does not exist
// out = Files.newOutputStream(path, APPEND);
Files.newOutputStream(path, StandardOpenOption.APPEND)
To keep the file at the same size, you need to calculate how much room left in the file and open LimitedOutputStream accordingly.
public synchronized void writeToAFile(String msg, String filePath) {
Path path = FileSystems.getDefault().getPath(filePath);
final long fileLength = path.toFile().length();
final long SIZE_1GB = 1073741824L;
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new LimitedOutputStream(Files.newOutputStream(path, StandardOpenOption.APPEND), SIZE_1GB - fileLength), StandardCharsets.UTF_8))) {
writer.append(msg);
} catch (Exception e) {
LOGGER.error("Something went wrong while writing to the file {} ", e.getMessage());
e.printStackTrace();
}
}
There are two methods, one for writing a line to a file, the other for reading.
public void onSaveButtonClick(View view) {
String text = binding.etSave.getText().toString();
if (text.isEmpty()) {
Toast.makeText(this, R.string.empty_text_error, Toast.LENGTH_SHORT).show();
return;
}
File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), FILE_NAME);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(text);
Log.d("logtest write", text);
} catch (IOException e) {
e.printStackTrace();
}
}
public void onReadButtonClick(View view) {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), FILE_NAME);
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String text = reader.readLine();
Log.d("logtest read", text);
binding.etLoad.setText(text);
} catch (IOException e) {
e.printStackTrace();
}
}
I'm conducting an experiment, writing new data to a file, subtracting it from a file, and seeing new data. I turn off the battery, reconnect, start the device and software, read the data - the data is old. No new data has been saved.
As I understand, at the first reading I get cached data that the OS does not have time to physically record due to an emergency power outage. Am I right or not? And how can I solve this problem?
I really need help with Java io manipulation of Streams. I don't know why this won't show me the contents of the file. I need to be able to view the text in this binary file "Data.abc" If I can view the contents of this file, i need to create a switch case condition to display it's contents per row / column.
Everytime I run the program, it returns some weird letters and characters like � NAme Address�����
Please help. I'm new to manipulation of streams. Thanks.
package IO_ReadFile;
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
InputStream istream; // creates an Input Stream and named it "istream"
OutputStream ostream; // creates an Output Stream and named it "ostream"
File inputFile = new File("Data.abc"); //passes file as argument
int c;
final int EOF=-1;
ostream = System.out;
try
{
istream = new FileInputStream(inputFile);
try
{
while((c=istream.read()) !=EOF)
ostream.write(c);
}
catch(IOException e)
{
System.out.println("Error: " + e.getMessage());
}
finally
{
try
{
istream.close();
ostream.close();
}
catch(IOException e)
{
System.out.println("File did not close");
}
}
}
catch(FileNotFoundException e)
{
System.exit(1);
}
}
}
I am trying to enter data into a text file from a java program. The program is executing and showing the output as success but when i open the text file it is still blank.
Here is my code
package com.example.ex2;
import java.io.*;
class Input{
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("abc.txt");
String s="Good MOrning";
byte b[]=s.getBytes();
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){
System.out.println(e);}
}
}
I think i have gone wrong in placing the text file. I have placed it in the default directory.
Your code works fine. Check the correct file.
If you are running from IDE, it will be in the current working directory.
It is always better to your a temp or directory to store files ( certainly not in working dir)
Here is a best practice code. You can tune it further if you wish
public static void main(String args[])
{
FileOutputStream fout = null;
try
{
File f = new File("abc.txt");
if (!f.isFile())
f.createNewFile();
fout = new FileOutputStream(f);
String s = "Good MOrning";
byte b[] = s.getBytes();
fout.write(b);
System.out.println("success... printed at : " + f.getAbsolutePath());
} catch (Exception e)
{
System.out.println(e);
} finally
{
if (null != fout)
try
{
fout.close();
} catch (IOException e)
{
}
}
}
I have a java application that needs to write a lot of data into individual lines in a text file. I wrote the code below to do this, but for some reason, it is not writing anything to the text file. It does create the text file, but the text file remains empty after the program is done running. Can anyone show me how to fix the code below so that it actually fills the output file with as many lines of output as it is called upon to do?
public class MyMainClass{
PrintWriter output;
MyMainClass(){
try {output = new PrintWriter("somefile.txt");}
catch (FileNotFoundException e1) {e1.printStackTrace();}
anotherMethod();
}
void anotherMethod(){
output.println("print some variables");
MyOtherClass other = new MyOtherClass();
other.someMethod(this);
}
}
public class MyOtherClass(){
void someMethod(MyMainClass mmc){
mmc.output.println("print some other variables")
}
}
How you are going about doing this seems very strange to me. Why don't you write one method that takes in a string and then writes it to your file? Something like this should work fine
public static void writeToLog(String inString)
{
File f = new File("yourFile.txt");
boolean existsFlag = f.exists();
if(!existsFlag)
{
try {
f.createNewFile();
} catch (IOException e) {
System.out.println("could not create new log file");
e.printStackTrace();
}
}
FileWriter fstream;
try {
fstream = new FileWriter(f, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(inString+"\n");
out.newLine();
out.close();
} catch (IOException e) {
System.out.println("could not write to the file");
e.printStackTrace();
}
return;
}
Use the other constructor:
output = new PrintWriter(new FileWriter("somefile.txt"), true);
According to JavaDoc:
public PrintWriter(Writer out, boolean autoFlush)
Creates a new PrintWriter.
Parameters:
out - A character-output stream
autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer
Use other constructor new PrintWriter(new PrintWriter("fileName"), true) for auto-flushing data or
Use flush() and close() when you're done writing