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");
}
Related
I'm trying to write a method for a program that only reads the last line of the text file, but I can't find out what the issue is and I have been searching for a while. Any help would be amazing.
public String getLastLine(String path) throws IOException {
String st;
String ot = null;
try {
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
while ((st = br.readLine()) != null) {
ot = st;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return ot;
}
Everything I have been able to find tells me to create a string and set it to null or to set it to "", but this isn't working at all for me. I keep getting this error code
org.junit.ComparisonFailure: expected:<[BZHbzAauZi]> but was:<[]>
I tried to return the last line of a text file but it only returns as a empty space.
while ((st = br.readLine()) != null)
{
if(st.isBlank()) {
continue;
}
ot = st;
}
Will preserve the last-read, non-blank line.
What i'm trying to do, is to replace a symbol in a file text which contains over 4000 lines but using the below code, after the program ends, it only remain 500 lines. Why is this file truncated? How to solve this?
This is my code:
ArrayList<String> arrayList = new ArrayList<>();
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {System.err.println(e);}
}
} catch (Exception e) {e.printStackTrace();}
Thanks in advance!
new BufferedWriter(new FileWriter(file)) clear file.
You should open it only once. Also you reading and writing to the same file. You should use different files.
Like this
try (FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
bw.write(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
You are writing to the same file while you are reading it. This won't work. Once you start writing, the file becomes empty (plus whatever you've written), so subsequent reads will report end-of-file. Your ~500 lines will be buffered input from the first read.
One solution is to do all the reading first, before opening the file again for writing:
Array<String> arrayList = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
while ((String line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {
System.err.println(e);
}
Here, first the program slurps the file into a List<String>, fixing the lines as it goes. Then it writes all the lines back out to the file.
There are circumstances in which this model is appropriate. For example, you might be building a non-linear data structure from the file content. Or you might need to see the last line before you can modify earlier lines (and be unable to re-open the data source from the start).
However I'd suggest a method that's more thrifty with memory. You don't need to keep all those lines in memory. You can read one line, fix it up, then forget about it. But to do this, you'll need to write to a second file.
String filein = "inputfile";
String fileout = filein + ".tmp";
try(
BufferedReader reader = new BufferedReader(new FileReader(filein));
Writer writer = new BufferedWriter(FileWriter(fileout))
) {
while ((String line = bufferedReader.readLine()) != null) {
writer.write(line.replace("þ", "t");
}
}
Files.move(Paths.get(fileout)),
Paths.get(filein),
CopyOption.REPLACE_EXISTING);
I have left out the necessary exception catching -- add back in as required.
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.
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?
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);