So i have recently dove head first into java trying to learn lots of things. Recently i have been studying File Writers and Reader and Buffered Writers and Readers. I have recently came to a haul though every time i turn on the application the text file is modified agian. Is there a way that my text file can update every time i change a string. So basically it will read the file on boot and compare it to the string.
Here is my example of reading a text file and turning it into a string
private void Read() {
try(BufferedReader br = new BufferedReader(new FileReader(version))) {
String sCurrentLine;
while((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch(IOException e) {
e.printStackTrace();
}
}
All i need to do is it to compare this string with another. Thank you for your time.
** Update**
So i compared the two threads and now nothing is being written to the text file
private void Update() {
try {
fw= new FileWriter(version.getAbsoluteFile());
bw = new BufferedWriter(fw);
try(BufferedReader br = new BufferedReader(new FileReader(version))) {
String sCurrentLine;
while((sCurrentLine = br.readLine()) != null) {
if(!sCurrentLine.equals(VanoEngine.TITLE)) {
bw.write(VanoEngine.TITLE);
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
catch(IOException e) {
e.printStackTrace();
}
}
** Update**
Closed the stream #JavaNoob and still nothing is being written
private void Update() {
try {
fw= new FileWriter(version.getAbsoluteFile());
bw = new BufferedWriter(fw);
try(BufferedReader br = new BufferedReader(new FileReader(version))) {
String sCurrentLine;
while((sCurrentLine = br.readLine()) != null) {
if(!sCurrentLine.equals(VanoEngine.TITLE)) {
bw.write(VanoEngine.TITLE);
}
}
bw.close();
} catch(IOException e) {
e.printStackTrace();
}
}
catch(IOException e) {
e.printStackTrace();
}
}
if(!sCurrentLine.equals(someInputString))
//write `someInputString` to file, because it differs with the one read from file
you can use sCurrentLine.equals("your string").
Related
I am trying to do same in Eclipse to print a text file and highlight a particular line, but am only able to read text file and not the line in it. Following is my code:
import java.io.*;
public class Bible {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("temp.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Correct code to read a file line by line is
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
//br = new BufferedReader(new FileReader(FILENAME));
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Now comes the code to highlight.
There are multiple options to do it.
Use html codes in file e.g.
origString = origString.replaceAll(textToHighlight,"<font color='red'>"+textToHighlight+"</font>");
Textview.setText(Html.fromHtml(origString));
Use spannable texts
String text = "Test";
Spannable spanText = Spannable.Factory.getInstance().newSpannable(text);
spanText.setSpan(new BackgroundColorSpan(0xFFFFFF00), 14, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spanText);
Use some third party library
EmphasisTextView and
Android TextView Link Builder
I'm making a project where using java I / O
I have a file with the following data:
170631|0645| |002014 | 0713056699|000000278500
155414|0606| |002014 | 0913042385|000001220000
000002|0000|0000|00000000000|0000000000000000|000000299512
and the output I want is as follows:
170631
0645
002014
file so that the data will be decreased down
and this is my source code:
public class Tes {
public static void main(String[] args) throws IOException{
File file;
BufferedReader br =null;
FileOutputStream fop = null;
try {
String content = "";
String s;
file = new File("E:/split/OUT/Berhasil.RPT");
fop = new FileOutputStream(file);
br = new BufferedReader(new FileReader("E:/split/11072014/01434.RPT"));
if (!file.exists()) {
file.createNewFile();
}
while ((s = br.readLine()) != null ) {
for (String retVal : s.split("\\|")) {
String data = content.concat(retVal);
System.out.println(data.trim());
byte[] buffer = data.getBytes();
fop.write(buffer);
fop.flush();
fop.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want is to generate output as above from the data that has been entered
File Input -> Split -> File Output
thanks :)
I think you forgot to mention what problem are you facing. Just by looking at the code it seems like you are closing the fop(FileOutputStream) every time you are looping while writing the split line. The outputStream should be closed once you have written everything, outside the while loop.
import java.io.*;
public class FileReadWrite {
public static void main(String[] args) {
try {
FileReader inputFileReader = new FileReader(new File("E:/split/11072014/01434.RPT"));
FileWriter outputFileWriter = new FileWriter(new File("E:/split/11072014/Berhasil.RPT"));
BufferedReader bufferedReader = new BufferedReader(inputFileReader);
BufferedWriter bufferedWriter = new BufferedWriter(outputFileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
for (String splitItem : line.split("|")) {
bufferedWriter.write(splitItem + "\n");
}
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've been working on a personal app and Stack Overflow has helped a bit so far, but I've now run into another issue. I'm attempting to read a basic text file stored in my source code and output it to an alert dialog. My code does this, but the dialog does not display any of my new lines.
displayChangelogDialog method
private void displayChangelogDialog() {
Context context = this;
AssetManager am = context.getAssets();
InputStream is;
// ensure that changelog is available
try {
is = am.open("changelog");
// changelog dialog
new AlertDialog.Builder(this)
.setTitle("Changelog")
.setMessage(getStringFromInputStream(is)) // convert changelog to string
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
} catch (IOException e) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
getStringFromInputStream method
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
changelog text file
v0.0.3
- Update PPS rate for recent difficulty increase
v0.0.2
- Calculate DGM based on PPS rate
I have attempted to add "\n" to the end of each line, but it does not work and the characters "\n" are simply displayed. Thanks in advance everyone.
There is an easy and hack way to read all of the inputstream into a string object which contains all you need without read line by line.
Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");
String string = scanner.hasNext() ? scanner.next() : null;
scanner.close();
readLine() will read up to a linefeed, but not include the linefeed. Also, there is no reason to use a string builder here. Change to this:
String result = "";
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
result += line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
I am passing a file path to this method which writes the in txt file. But when I run this program it is not writing full and I don't know where I made mistake.
public void content(String s) {
try {
BufferedReader br=new BufferedReader(new FileReader(s));
try {
String read=s;
while((read = br.readLine()) != null) {
PrintWriter out = new PrintWriter(new FileWriter("e:\\OP.txt"));
out.write(read);
out.close();
}
} catch(Exception e) { }
} catch(Exception e) { }
}
You shouldn't create your PrintWriter inside the loop every time:
public void content(String s) {
BufferedReader br=new BufferedReader(new FileReader(s));
try {
PrintWriter out=new PrintWriter(new FileWriter("e:\\OP.txt"));
String read=null;
while((read=br.readLine())!=null) {
out.write(read);
}
} catch(Exception e) {
//do something meaningfull}
} finally {
out.close();
}
}
Aditionally, as others have mentioned add a finally block, do not silently catch the exception, and follow the Java Coding Conventions.
close your PrintWriter inside finally block out side the loop
finally {
out.close();
}
It's better to use Apache Commons IO instead.
http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html should make the trick.
(Unless you are trying to learn the low-level stuff or actually knows why you can't use IOUtils for this case.)
try this
public void content(String s) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(s));
PrintWriter pr = new PrintWriter(new File("e:\\OP.txt"))) {
for (String line; (line = br.readLine()) != null;) {
pr.println(line);
}
}
}
Your closing stream before finishing it. So either put it into
<code>
finally {
out.close();
}
</code>
or see this simple example
<code>try {
String content = s;
File file = new File("/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
</code>
I used following method to write data to a file in one android application
private void writeFileToInternalStorage() {
String eol = System.getProperty("line.separator");
BufferedWriter writer = null;
try{
writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("myFile.txt", MODE_WORLD_WRITEABLE|MODE_WORLD_READABLE)));
writer.write("Hello world!");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (writer != null)
{
try
{
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Then I tried to read that file from another android application using this method
private void readFileFromInternalStorage(){
String eol = System.getProperty("line.separator");
BufferedReader input = null;
try
{
input = new BufferedReader(new InputStreamReader(openFileInput("myFile1.txt")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null)
{
buffer.append(line + eol);
}
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(buffer.toString().trim());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (input != null)
{
try
{
input.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Second method can't read the file. I added read write permissions also, but it shows only blank screen. What can be the error and how can I correct that ??. I'm new to Android programming and need your help.
Thanks!
The problem is
openFileOutput("myFile.txt", MODE_WORLD_WRITEABLE|MODE_WORLD_READABLE))
The documentation says:
This file is written to a path relative to your app within the
So the case is you are writing file in path relative to application 1 and trying to read it from
path relative to application 2.
You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
Look below snippet to write file to SD card.
private void writeToSDCard() {
try
{
File file = new File(Environment.getExternalStorageDirectory(),
"filename");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello World");
writer.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Look below snippet to read file saved on SD card.
private void readFileFromSDCard() {
File directory = Environment.getExternalStorageDirectory();
// Assumes that a file article.rss is available on the SD card
File file = new File(directory + "/article.rss");
if (!file.exists()) {
throw new RuntimeException("File not found");
}
Log.e("Testing", "Starting to read");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Your best bet is to place it into the scdcard into something like /sdcard/Android/data/package/shared/