Loading break line sign "\n" from file - java

I need to load from text file text which I will be replacing in other string.
For example I have text file:
\n;(br)
After loading this file I need to change all break lines to (br) so I will receive one line string.
Problems is when I'm loading text from file - I don't get string \n;(br) but \\n;(br)
Anyone know how to do that?
My code - I know that I'm adding '\n' in method applyFilters but it is because that there can be situation when I don't whant to change that.
void loadSource(){
File file = new File(sourcePath);
BufferedReader reader=null;
String text;
try{
reader = new BufferedReader( new FileReader(file));
}catch(FileNotFoundException e){
e.printStackTrace();
}
try{
while((text = reader.readLine()) != null){
sourceText.add(text);
}
}catch(Exception e){
e.printStackTrace();
}
}
void loadFilters(){
File file = new File(filterPath);
BufferedReader reader=null;
String text;
try{
reader = new BufferedReader( new FileReader(file));
}catch(FileNotFoundException e){
System.out.println("Błąd, brak pliku źródłowego");
e.printStackTrace();
}
try{
while((text = reader.readLine()) != null){
filterText.add(text);
}
}catch(Exception e){
e.printStackTrace();
}
}
void applyFilters(){
for (String s : sourceText){
finalText = finalText+ s + "\n";
}
for(String filter : filterText)
{
finalText = finalText.replace(filter.split(";")[0],filter.split(";")[1]);
}
System.out.println(finalText);
}

It sounds like you want the "\n" in your text file to represent a newline character rather than a backslash followed by an n. Have a look at this question:
How to unescape a Java string literal in Java?

Related

BufferedReader returns file that does not match the original

I am using a BufferedReader to read a file and store each line in a String ArrayList. However, after running the BufferedReader, reading the file, storing it, and printing the ArrayList, I get something different from the original file.
My code to read file:
public File shooterUIFile = new File("./src/com/xyfurion/hudedit/bin/resources/ShooterUI.ini");
public ArrayList<String> shooterUIRead = new ArrayList<>();
public ArrayList<String> shooterUIWrote = new ArrayList<>();
public void readHUDFile(){
try {
FileReader fileReader = new FileReader(shooterUIFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while (bufferedReader.readLine() != null)
shooterUIRead.add(bufferedReader.readLine());
for (int i = 0; i < shooterUIRead.size(); i++)
System.out.println(shooterUIRead.get(i));
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + shooterUIFile + "'");
ex.printStackTrace();
}
catch(IOException ex) {
System.out.println("Error reading file '" + shooterUIFile + "'");
ex.printStackTrace();
}
}
Output (File printed): PASTEBIN
Original File: PASTEBIN
You are only keeping every other line , since you are calling readLine twice each iteration and discarding the first read line (the one in the while condition).
You may avoid it this way :
String line = null;
while ((line = bufferedReader.readLine()) != null)
shooterUIRead.add(line);

Why can't I neither delete nor rename the file?

While creating a method to my class, I got an unexpected problem. I've tried solutions from other theards, but they just don't work for me. My method should simply find the line specified, copy the file skipping unnecessary line, delete the original file and rename temporary file to the name of original file. It succesfuly creates new file as expected, but then fails to delete previous one as it fails to rename temporary file to original. I can't figure out, why?
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
File filePath = new File(path);
BufferedReader reader = new BufferedReader(new FileReader(file_name + ".txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
filePath.delete();
temp.renameTo(theFile);
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
Try this code:
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
BufferedReader reader = new BufferedReader(new FileReader(theFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
theFile.delete();
temp.renameTo(file_name + ".txt");
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
I could suggest a couple of reasons why the delete and/or rename might fail, but there is a better way to solve your problem than guessing1.
If you use Path and the Files.delete(Path) and Files.move(Path, Path, CopyOption...) methods, they will throw exceptions if the operations fail. The exception name and message should give you clues as to what is actually going wrong.
The javadoc is here and here.
1 - Here are a couple of guesses: 1) the file has been opened elsewhere, and it is locked as a result. 2) You don't have access to delete the file.

Reading a file's name from a text field and displaying it

I'm trying to make a program that reads a file name through a text field and displays it in a text area. I will also need a clear button. This is what I have so far:
private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
String fileName = jTextField1.getText();
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String s;
while ((s = br.readLine()) != null) {
jTextArea1.setText(s + "\n");
}
br.close();
} catch (IOException e) {
jTextArea1.setText("File not found!");
}
}
private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText("");
jTextArea1.setText("");
}
For some reason, it is not reading my text file on my desktop, called "hi". How could I make my program work? What am I doing wrong?
setText does that, sets the text of the field
Now, JTextArea has a simple read method for reading content, for example
try (BufferedReader reader = new BufferedReader(new FileReader(new File("resources/New Text Document.txt")))) {
textArea.read(reader, "File");
} catch (IOException exp) {
exp.printStackTrace();
}
I'm not sure about your problem but this seems not right to me and I want to mention to you to fix it:
Actually what you do is putting the last line of text in your textArea1 and if your last line is "\n" or an empty line, then obviously you don't see anything on your screen.
It would be good to use StringBuffer to store your lines which are read from the file and display the whole text. The following code can help you:
StringBuffer buffer = new StringBuffer();
String s;
while ((s = br.readLine()) != null) {
buffer.append(s).append('\n');
}
jTextArea1.setText(buffer.toString());
your code is actually working and it is reading the file, but your code goes wrong inside the while loop when you are assigning the value you are not concating string inside the while loop i have made some changes to your code try this one.
String fileName = "src/hi.txt";
String content = "";
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String s;
while ((s = br.readLine()) != null) {
content+="\n"+s;
}
System.out.println(content);
br.close();
} catch (Exception e) {
System.out.println("file not found");
}

Reading from a text file in java is returning some garbage value

I'm performing certain commands through command prompt and storing the values in a text file.
wmic logicaldisk where drivetype=3 get deviceid > drive.txt
Now I want to read the string stored in the text file from my java file. When I try to do this:
try {
File file = new File("drive.txt");
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
int i=0;
while ((string[i] = in.readLine()) != null) {
System.out.println(string[i]);
++i;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
I get the output as follows:
ÿþD[]E[]V[]I[]C[]E[]
how to avoid this?
while ((string[i] = in.readLine()) != null) {
System.out.println(string[2]);
}
over there you are missing the i++;
However I would advise you to use this structure: Use a ArrayList instead of an array, since this allows you to have a self-resizing structure, also instead in the while use the method ready(); from the BufferedRead in order to check the end from the document, at the end the for it's just to display the elements in String ArrayList.
ArrayList<String> string = new ArrayList<String>();
try {
File file = new File("drive.txt");
BufferedReader entrada;
entrada = new BufferedReader(new FileReader(file));
entrada.readLine();
while (entrada.ready()) {
string.add(entrada.readLine());
}
entrada.close();
} catch (IOException e) {
e.printStackTrace();
}
for (String elements : string) {
System.out.println(elements);
}
Why do you need a string array here? The size of the array may be wrong? Simply use a string instead of array. I tried this and works fine for me:
try {
String string;
File file = new File("drive.txt");
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
int i = 0;
while ((string = in.readLine()) != null) {
System.out.println(string);
++i;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
If you are using eclipse IDE, change the encoding type. Go to Edit->Set Encoding-> Others->UTF-8.

Inserting a big text file into netbeans

try {
BufferedReader br = new BufferedReader(new FileReader("Help.txt"));
String helptext = br.readLine();
helpText.setText(helptext);
} catch (IOException e) {
System.out.println ("Error: " + e);
}
It only returns the first line of the text file and the text file is about 4 pages long.
"helptext" being a text area.I want the whole file with its spaces I made in the text area.
This will give only 1 line where in your file the first line whatever contain to get all the line you need get into the loop
StringBuffer sb = new StringBuffer();
String line = null;
while((line=br.readLine()) !=null){
sb.append(line);
}
helpText.setText(sb.toString());
You need to loop through the text file. You are only telling it to readline() one time.
EDIT: Fixed code to be exactly what user needed
EDIT 2: Added code to keep cursor at top
String line;
try {
BufferedReader br = new BufferedReader(new FileReader("<Location of text file>"));
while((line=br.readLine()) != null){
helpText.append(line);
//Add a new line for the next entry (If you would like)
helpText.append("\n");
}
//Set Cursor back to start
helpText.setCaretPosition(WIDTH);
}
catch (IOException e) {
System.out.println (e);
}
you have to read every line in a loop.
String line = br.readLine();
String helptext = "";
while(line != null) {
helptext = helptext + line;
line = br.readLine();
}
helpText.setText(helptext);

Categories