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);
Related
This question already has answers here:
BufferedReader is skipping every other line when reading my file in java
(3 answers)
Closed 4 months ago.
I'm trying to read nearly 120,000 lines from a file, put the data into a new record, and add this record to a list.
My problem is that I can't load all the data getting weird behavior.
In particular, using BufferedReader a first time I can count the rows and the result is correct, but when I try with a while loop to load the data into memory I see that the loop iterates about 60,000 times and the final list with the data contains only about 5000 objects.
I've also tried using other classes for loading data, but I always get the same problem.
I am currently using java 17 with spring and javafx.
Thank you.
I am attaching the latest version of my method:
public void getFixList(FixReadyCallback callback) {
List<Fix> fixList;
int firstCount = 0;
int whileCount = 0;
try {
File file = new File("src/main/resources/fligh_data/fix.dat");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String currentLine = null;
while (reader.readLine() != null) {
firstCount++;
}
fixList = new ArrayList<>(firstCount);
reader.close();
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while ((currentLine = reader.readLine()) != null) {
whileCount++;
currentLine = reader.readLine();
if (currentLine.matches(
"[-]?[0-9]{2}\\.[0-9]{6}\\s+[-]?[0-9]{3}\\.[0-9]{6}\\s+[0-9A-Z]{2,5}")) {
String[] splitted = currentLine.split("\\s+");
String denomination = splitted[2];
double latitude = Double.parseDouble(splitted[0]);
double longitude = Double.parseDouble(splitted[1]);
Coordinates coordinates = new Coordinates(latitude, longitude);
fixList.add(new Fix(denomination, coordinates));
}
}
System.out.println("FIRST_COUNT -> " + firstCount);
System.out.println("WHILE_COUNT -> " + whileCount);
System.out.println("LIST_SIZE -> " + fixList.size());
reader.close();
callback.onReady(fixList);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And the output of the terminal:
FIRST_COUNT -> 119724
WHILE_COUNT -> 59862
LIST_SIZE -> 5128
while ((currentLine = reader.readLine()) != null) {
whileCount++;
currentLine = reader.readLine();
...
}
This skips every other line in your file. currentLine is already the next line in the file, and then you overwrite it with the line after that. I think you only meant to read one line per loop.
It seems pretty clear that you should simply delete the last line I quoted:
while ((currentLine = reader.readLine()) != null) {
whileCount++;
...
}
I trying to remove a specific line from a file. But I have a problem in deleting a particular line from the text file. Let's said, my text file I want to remove Blueberry in the file following:
Old List Text file:
Chocolate
Strawberry
Blueberry
Mango
New List Text file:
Chocolate
Strawberry
Mango
I tried to run my Java program, when I input for delete and it didn't remove the line from the text file.
Output:
Please delete:
d
Blueberry
Remove:Blueberry
When I open my text file, it keep on looping with the word "Blueberry" only.
Text file:
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
My question is how to delete the specific line from the text file?
Here is my Java code:
String input="Please delete: ";
System.out.println(input);
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader (System.in));
line = reader.readLine();
String inFile="list.txt";
String line = "";
while(!line.equals("x"))
{
switch(line)
{
case "d":
line = reader.readLine();
System.out.println("Remove: " + line);
String lineToRemove="";
FileWriter removeLine=new FileWriter(inFile);
BufferedWriter change=new BufferedWriter(removeLine);
PrintWriter replace=new PrintWriter(change);
while (line != null) {
if (!line.trim().equals(lineToRemove))
{
replace.println(line);
replace.flush();
}
}
replace.close();
change.close();
break;
}
System.out.println(input);
line = reader.readLine();
}
}
catch(Exception e){
System.out.println("Error!");
}
Let's take a quick look at your code...
line = reader.readLine();
//...
while (line != null) {
if (!line.trim().equals(lineToRemove))
{
replace.println(line);
replace.flush();
}
}
Basically, you read the first line of the file and then repeatedly compare it with the lineToRemove, forever. This loop is never going to exit
This is a proof of concept, you will need to modify it to your needs.
Basically, what you need to ensure you're doing, is you're reading each line of the input file until there are no more lines
// All the important information
String inputFileName = "...";
String outputFileName = "...";
String lineToRemove = "...";
// The traps any possible read/write exceptions which might occur
try {
File inputFile = new File(inputFileName);
File outputFile = new File(outputFileName);
// Open the reader/writer, this ensure that's encapsulated
// in a try-with-resource block, automatically closing
// the resources regardless of how the block exists
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
// Read each line from the reader and compare it with
// with the line to remove and write if required
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.equals(lineToRemove)) {
writer.write(line);
writer.newLine();
}
}
}
// This is some magic, because of the compounding try blocks
// this section will only be called if the above try block
// exited without throwing an exception, so we're now safe
// to update the input file
// If you want two files at the end of his process, don't do
// this, this assumes you want to update and replace the
// original file
// Delete the original file, you might consider renaming it
// to some backup file
if (inputFile.delete()) {
// Rename the output file to the input file
if (!outputFile.renameTo(inputFile)) {
throw new IOException("Could not rename " + outputFileName + " to " + inputFileName);
}
} else {
throw new IOException("Could not delete original input file " + inputFileName);
}
} catch (IOException ex) {
// Handle any exceptions
ex.printStackTrace();
}
Have a look at Basic I/O and The try-with-resources Statement for some more details
Reading input from console, reading file and writing to a file needs to be distinguished and done separately. you can not read and write file at the same time. you are not even reading your file. you are just comparing your console input indefinitely in your while loop.In fact, you are not even setting your lineTobeRemoved to the input line. Here is one way of doing it.
Algorithm:
Read the console input (your line to delete) then start reading the file and looking for line to delete by comparing it with your input line. if the lines do not match match then store the read line in a variable otherwise throw this line since you want to delete it.
Once finished reading, start writing the stored lines on the file. Now you will have updated file with one line removed.
public static void main(String args[]) {
String input = "Please delete: ";
System.out.println(input);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String line = reader.readLine();
reader.close();
String inFile = "list.txt";
System.out.println("Remove: " + line);
String lineToRemove = line;
StringBuffer newContent = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader(inFile));
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
newContent.append(line);
newContent.append("\n"); // new line
}
}
br.close();
FileWriter removeLine = new FileWriter(inFile);
BufferedWriter change = new BufferedWriter(removeLine);
PrintWriter replace = new PrintWriter(change);
replace.write(newContent.toString());
replace.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
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");
}
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?
Here is my code:
try {
String textLine;
FileReader fr = new FileReader("ad.txt");
BufferedReader reader = new BufferedReader(fr);
while((textLine=reader.readLine()) != null) {
textLine = reader.readLine();
jTextArea1.read(reader, "jTextArea1");
}
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
And my .txt file contains the following:
contig00001 length=586 numreads=4
CGGGAAATTATCcGCGCCTTCACCGCCGCCGGTTCCACCGACGAACGGATACTGCGtGaa
ggCCGCGATCCCGTCggaCGGAAAaCGCCcTGGCCCGGGAaCATACCGTTCGGGCCGCCA
AGTGTTATAGCCGGACCACTTGTCAGAACATTTCCaaTCCGAAGATGTGAGTtCGGAAGg
TAAAAGCCCGACAAGTTGCGCGgTGAATTTACCTTtACcGCACGATATGCGTCCGTATTA
AaGAAAaGTTCGAAATTATCAGTAAGGCCGACCTGAAaGCTGACCGGGAGTTCAACAAAA
TCTGCATCACCcGGgTCACGGTCGAAATTGCTGTACGCGGCGCTGAACGTAAATTCACCC
TTTcTAAGGGTGTCGCcGTCGTAAACCGTAAaCAaGCCGGTAGCGCCGCCCATCGGGCCG
CCGGTACCAACCGTCGGTGCCGTGTTTCTtGCATCATTGTCCGATCGAGCGTTCTCGTCC
GCTTGTGCAAaTCCTGCAaTAGCTAACGTGAAAACGATCAGAGCTGTTGTAAATACTCTA
TAAGCGAGATTCATCACATTCCTCcGCCGAAATAAAAAGTTAATTt
contig00002 length=554 numreads=4
TGCGCCAaCCGCGCTCTtCATAAaTGGGCACTGCTCCCGATGGCCgACTCGGGCGGTTCG
CCATGAGATCTTTGCCtACCcAGgAaCtCACcACCAAGTCTGATTGCTGTGTGTTTtCTT
CAAGTCCCTATTTCTATTCtCTTtAATGGAACCCGTAGGAAACCCGTGTAGGACGCGGGA
aCCGCACTTgAAGGGGGAGGCGCGGGGTACCGGtCCGGGAACGTACGGGTACCGGCGGGG
gAGGGGAGGGGGACCgCTCCGGGAAGGCCAGGGGACGGATTGGGGAAGGgCGGGTACCGA
AGCGGGgAAaTGGGggAaCcGGCGAGAGGGTTCCTCGCTAAGTGGGGGAAATaGGGGAAA
GGTTGACCAGTGGTtCCCcGCTCTCGTAACATGCCTCAGATAGCGCCATCCGCTGTACCT
GGtcaggtcGctggcaacttcggccgagcaggtgaacccgaaaggtgagggtcagtgtga
cacaccaaccgaacaccgacgaggcaagcgtaggagccggcgtggccgcgcccggcggcg
ctgaggactcctcg
But shows the output by skipping the first two lines.
What is the reason for this?
You don't need the while loop, or the readLine method. Just call jtextArea1.read(reader, "jTextArea1")
Edit: update following your comment. If you want to skip all lines starting with >, you will need to read the file manually and then append each line to your textArea.
So something like:
String line;
while ((line = reader.readLine()) != null)
{
if (!line.startsWith(">"))
{
jTextArea.append(line + "\n");
}
}
Use:
FileReader reader = new FileReader("filename.txt");
txtarea.read(reader, "filename.txt"); //Object of JTextArea
You need only the above two lines to read from a file and put it into JTextArea...
The problem must have been solved by the time, yet there's still no answer to the question why the first two lines are skipped.
You create reader and then read the first two lines from the file, remaining lines are loaded into jTextArea1.
Your code:
/* 1 */ while((textLine=reader.readLine())!=null){
/* 2 */ textLine = reader.readLine();
/* 3 */ jTextArea1.read(reader,"jTextArea1");
}
Line 1 reads the first line from the file. Then in the body of while you read the second line from the file at line 2. Line 3 reads the rest of the file into jTextArea1.
On the next iteration of the while loop, reader.readLine() returns null since the file is completely read.
To load text in a JTextComponent use its read method as suggested by Phill and Bhushankumar.
The second parameter to read is not used by JTextArea, so it's safe to pass null. This second parameter is usually used to store to URL of the loaded file to resolve relative references, for example links in an HTMLDocument.
textLine = reader.readLine(); is called twice...
Fixed:
try {
String textLine;
FileReader fr = new FileReader("ad.txt");
BufferedReader reader = new BufferedReader(fr);
while((textLine=reader.readLine()) != null){
// textLine = reader.readLine(); // Remove this line
jTextArea1.read(reader, "jTextArea1");
}
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
Correctly is:
try {
FileReader fr = new FileReader("tablica.txt");
BufferedReader reader = new BufferedReader(fr);
do {
l.read(reader, null);
}
while ((textLine=reader.readLine()) != null)
;
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}