BufferedReader creating odd characters, which character encoding do I use? - java

I am trying to take multiple text files and merge them all in to one new file. However, looking at the new file that was created there are some weird characters that have replaced quotation marks and I can't figure out why or how this is occurring. Tried specifying the encoding but it did not solve the problem. Am I using the wrong character encoding?
Reader reader = new InputStreamReader(new FileInputStream(fileName), "utf-8");
Here is the issue:
Original file contains:
|3_PatFemale("X")|3_PatSex (”M” or “F”)|
New file contains
|3_PatFemale("X")|3_PatSex (�M� or �F�)|
code:
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile),"UTF-8"));
for (File f : files) {
FileInputStream fis;
try {
fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
out.write(aLine);
out.newLine();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Change the contents of the file form this
|3_PatFemale("X")|3_PatSex (”M” or “F”)|
to
|3_PatFemale("X")|3_PatSex ("M" or "F")|
The quotation you are using
”
(prime quotation mark)
is different from
"
For further reference: https://askleo.com/why_do_i_get_odd_characters_instead_of_quotes_in_my_documents/

Related

Read textfile line by line

I tried it this way but it doesn't find the textfile.
try {
FileInputStream fstream = new FileInputStream("textfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
All files are in the same package.
Your text file is inside a the package "trainer" which is inside "src" so when you request it, you must use "src/trainer/textfile.txt". The preceding / denotes the root of the application and is optional if you're not exporting to runnable jars for example.
FileInputStream fstream = new FileInputStream("src/trainer/textfile.txt");

Android/java Cant read from .txt file in local storage

So i have a .txt file in local storage its a simple text file. The text is basically just a series of lines.
I am using the code below to attempt to read the text file (i verify the file exists before calling this method).
public static String GetLocalMasterFileStream(String Operation) throws Exception {
//Get the text file
File file = new File("sdcard/CM3/advices/advice_master.txt");
if (file.canRead() == true) {System.out.println("-----Determined that file is readable");}
//Read text from file
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
System.out.println("-----" + line); //for producing test output
text.append('\n');
}
br.close();
System.out.print(text.toString());
return text.toString();
}
The code produces in the log
----Determined that file is readable
But that is the ONLY output the file data is not written to the log
Also i have tried inserting before the while loop the following to attempt to just read the first line
line = br.readLine();
System.out.println("-----" + line);
That produces the following output:
-----null
Check this out getExternalStorage
File path = Environment.getExternalStorageDirectory();
File file = new File(path, "textfile.txt");
//text file is copied in sdcard for example
Try to add a lead slash in file path /sdcard/CM3/advices/advice_master.txt
File file = new File("/sdcard/CM3/advices/advice_master.txt");
Try this. Just pass the txt file name as a parameter...
public void readFromFile(String fileName){
/*
InputStream ips;
ips = getClass().getResourceAsStream(fileName);
//reading
try{
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
String line;
while ((line = br.readLine())!=null){
//reading goes here ;)
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
*/
// or try this
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
}
Let me refine my answer. You can try another way to read all lines from advice_master.txt and see what happens. It makes sure that all file contents can be read.
Charset charset = Charset.forName("ISO-8859-1");
try {
List<String> lines = Files.readAllLines(Paths.get(YOUR_PATH), charset);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e);
}

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

Android: Append to file instead of ovewriting

I am trying to append to a text file but for some reason it keeps overwriting it, here's my code:
File logFile = new File(Environment.getExternalStorageDirectory().toString(), "notifications.txt");
try {
if(!logFile.exists()) {
logFile.createNewFile();
}
StringBuilder text = new StringBuilder(); // build the string
String line;
BufferedReader br = new BufferedReader(new FileReader(logFile)); //Buffered reader used to read the file
while ((line = br.readLine()) != null) { // if not empty continue
text.append(line);
text.append('\n');
}
BufferedWriter output = new BufferedWriter(new FileWriter(logFile));
output.write(text + "\n");
output.close();
alertDialog.show();
} catch (IOException ex) {
System.out.println(ex);
}
thank you in advance
use
new FileWriter(logFile, true)
Where the second parameter tells it to append, not overwrite.
Found in this question. In the related questions on the right.
Documentation can be found here
You need to use the other constructor of FileWriter that specifies whether the data is overwritten or appended. Use FileWriter(logFile, true) instead of what you have now :)

Reading a variable number of lines from a file

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

Categories

Resources