I am stuck at reading text from a file into text area.I don't know why but my file reader never opens the file even if it exists.I am getting file name from a text field and using a button listener to trigger this event.So any help will be appreciated. I've given my code to below.
try{
BufferedReader br = new BufferedReader(new FileReader(tf1.getText()));
while((read = br.readLine())!=null){
store = store + read;
}
ta.setText(store);
fr.close();
br.close();
jf2.dispose();
}
catch(Exception exp){
JOptionPane.showMessageDialog(null,"File Not Found.");
}
Change your code to something like this:
br = new BufferedReader(new FileReader(new File(tf1.getText())));
It is important to note that you need to have a "File" that encapsulates your text to open the actual file. Otherwise, the JVM does not know in which part of the harddisk to search for.
Good luck.
Related
I have a text file with some text in it and i'm planning on replacing certain characters in the text file. So for this i have to read the file using a buffered reader which wraps a file reader.
File file = new File("new.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
But since i have to edit characters i have to introduce a file writer and add the code which has a string method called replace all. so the overall code will look as given below.
File file = new File("new.txt");
FileWriter fw = new FileWriter(file);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
fw.write(br.readLine().replaceAll("t", "1") + "\n");
}
Problem is when i introduce a file writer to the code (By just having the initialization part and when i run the program it deletes the content in the file regardless of adding the following line)
fw.write(br.readLine().replaceAll("t", "1") + "\n");
Why is this occurring? am i following the correct approach to edit characters in a text file?
Or is there any other way of doing this?
Thank you.
public FileWriter(String fileName,
boolean append)
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the
file rather than the beginning.
To append data use
new FileWriter(file, true);
The problem is that you're trying to write to the file while you're reading from it. A better solution would be to create a second file, put the transformed data into it, then replace the first file with it when you're done. Or if you don't want to do that, read all of the data out of the file first, then open it for writing and write the transformed data.
Also, have you considered using a text-processing language solution such as awk, sed or perl: https://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files
You need to read the file first, and then, only after you read the entire file, you can write to it.
Or you open a different file for writing and then afterwards you replace the old file with the new one.
The reason is that once you start writing to a file, it is truncated (the data that was in the file is deleted).
The only way to avoid that is to open the file in "append" mode. With that mode, you start writing at the end of the file, so you don't delete its content. However, you won't be able to modify the existing content, you will only add content.
Maybe like this
public static void main(String[] args) throws IOException {
try {
File file = new File("/Users/alexanderkrum/IdeaProjects/printerTest/src/atmDep.txt");
Scanner myReader = new Scanner(file);
ArrayList<Integer> numbers = new ArrayList<>();
while (myReader.hasNextLine()) {
numbers.add(myReader.nextInt() + 1);
}
myReader.close();
FileWriter myWriter = new FileWriter(file);
for (Integer number :
numbers) {
myWriter.write(number.toString() + '\n');
}
myWriter.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Just add at last :
fw.close();
this will close it ,then it will not delete anything in the file.
:)
Here is the code but it does not delete storedIp file and rename tempFile to storedIP. Both file exist
String host=ipParsing(hostName);
File tempFile= new File("tempFile.txt");
File strFile = new File("StoredIp.txt");
BufferedReader bufferReader = new BufferedReader( new FileReader(strFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
String line;
while ((line = bufferReader.readLine()) != null) {
if(host.equals(line))
{
found=true;
line="";
}
bw.write(line);
if(!line.equals(""))
bw.newLine();
}
bw.close();
bufferReader.close();
strFile.delete();
tempFile.renameTo(new File ("StoredIP.txt"));
Well, a call to File.delete() does not necessary delete the file.
As the JavaDoc says: be sure to check the return value.
Ignoring this (like you did) is a common source of errors.
One occasion where this delete/renameTo easily goes awry, is when the files are in use. A solution seen consists of using an additional lock file. Too complicated for such a simple thing.
Using an embedded database, like java's own Derby, which is not that difficult. The database needs no extra provision. There are good tutorials with simple example code.
So I have a working code that is able to read the csv file but because the file is really big it takes roughly two minutes to read before all the data is displayed in an instant in the textarea. I'm using a GUI interface in eclipse with windowsbuilder. Below is the code;
JButton btnopen = new JButton("Open");
btnopen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
final JFileChooser fc = new JFileChooser(); //launching the file chooser
fc.setFileFilter(new FileNameExtensionFilter("Text Files", "txt")); //this will allow text files to be read
fc.setFileFilter(new FileNameExtensionFilter("CSV", "csv")); //this will allow csv files to be read
fc.setFileFilter(new FileNameExtensionFilter("JSON", "json")); //this will allow json files to be read
fc.setFileFilter(new FileNameExtensionFilter("XML", "xml")); //this will allow xml files to be read
int returnVal = fc.showOpenDialog(contentPane);
File f; //file that holds the data from the text file
fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter());
if(returnVal == JFileChooser.APPROVE_OPTION) {
f = fc.getSelectedFile(); //tells file chooser to get the file selected and store into file variable
String output="";
//use buffered reader and file reader to read selected file
BufferedReader in = new BufferedReader(new FileReader(f));
//after reading data, store in to string
String line = in.readLine(); //every time a line is read, data is put into text area
int i=0;
while(line!=null){ //while still reading...
//
line = in.readLine(); //continue reading next line of file
output +=line+"\n";
//textArea.append(line +"\n"); //add text from file into text area
//++i;
}
textArea.append(output);
}
}
catch(Exception e){
}
}
});
#HectorLector's response will optimize the reading a bit, but they're right; utltimately, reading a file is going to take as long as it takes. I suspect that your underlying question might be "how can I make my UI responsive while I'm reading this file?" - right now, since you're doing the reading inside an ActionListener, your UI will be completely blocked while the file is read, which makes for a terrible user experience.
The answer to this is that long-running operations like filesystem access should be done on a background thread. Consider using a SwingWorker (see the tutorial) for a task like this; the worker thread can build the string and use the done() method to update the text area (or, if you want to show the file as it's being read, use a combination of the publish() and process() methods).
Also, as a side note, be sure you're close()ing that BufferedReader you're using to read the file. Wrap the reading itself in a try block, and close inside finally in case there are any problems during reading. Something like this:
BufferedReader in = new BufferedReader(new FileReader(f));
StringBuilder output = new StringBuilder();
try {
while (in.hasNext()) {
output.append(in.readLine());
output.append("\n");
}
finally {
in.close();
}
Use a StringBuilder to create your string. Because strings are immutable a new object is created every time when you use "+" to append something.
This will increase performance but may not be the main problem.
Filesystem access is slow. Maybe try reading your file one time and keep it in memory (in a list or something). Or try only showing parts of the file at a time (paging).
BufferedReader in = new BufferedReader(new FileReader(f));
StringBuilder builder = new StringBuilder();
String line = "";
while((line = in.readLine()) != null){
builder.append(line);
builder.append("\n");
}
textArea.append(builder.toString());
I wrote the below part of the code but I couldn't bind the arraylist with search and replace
so my csv file is as like below
1/1/1;7/6/1
1/1/2;7/7/1
I want to search the file 1.cfg for 1/1/1 and change it to 7/6/1 and 1/1/2 change to 7/7/1 and it goes so on.
Thank you all in advance
It's now only printing in a new file only the last line of the old File
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ChangeConfiguration {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args)
{
try{
// Open the file that is the first
// command line parameter
FileInputStream degistirilecek = new FileInputStream("c:/Config_Changer.csv");
FileInputStream config = new FileInputStream("c:/1.cfg");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(config);
DataInputStream degistir = new DataInputStream(degistirilecek);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
BufferedReader brdegis = new BufferedReader(new InputStreamReader(degistir));
List<Object> arrayLines = new ArrayList<Object>();
Object contents;
while ((contents = brdegis.readLine()) != null)
{
arrayLines.add(contents);
}
System.out.println(arrayLines + "\n");
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//Couldn't modify this part error is here :(
BufferedWriter out = new BufferedWriter(new FileWriter("c:/1_new.cfg"));
out.write(strLine);
out.close();
}
in.close();
degistir.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
You are opening the file for reading when you declare:
BufferedReader br = new BufferedReader(new InputStreamReader(in));
If you know the entire file will fit in memory, I recommend doing the following :
Open the file and read it's contents in memory into a giant string, then close the file.
Apply your replace in one shot to the giant string.
Open the file and write (e.g use a BufferedWriter) out the contents of the giant string, then close the file.
As a side note, your code as posted will not compile. The quality of the responses you receive are correlated with the quality of the question asked. Always include an SCCE with your question to increase the chance of getting a precise answer to your question.
can you elaborate the purpose of the program?
if it is a simple content replacement in a file.
then just read a line and store it in a string. then use string replace method for replacing a text in a string.
eg:
newStrog=oldString.replace(oldVlue,newValue);
I'm trying to read a text file, i'm using fileImputStream, and reading all the lines into a single String then outputing it into the console (System.out)
When I try to read the humanSerf.txt, it gives me this in the consol:
{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf360
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\paperw11900\paperh16840\margl1440\margr1440\vieww9000\viewh8400\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural
\f0\fs24 \cf0 symbol=HS\
strength=15\
agility=13\
constitution=7\
wisdom=9\
intelligence=5}
in the text file, it says this:
symbol=HS
strength=15
agility=13
constitution=7
wisdom=9
intelligence=5
How do I make the weird text disappear?
this is the code i'm using, please help
try{
// Open the file that is the first
// command line parameter
FileInputStream read = new FileInputStream("resources/monsters/human/humanSerf.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(read);
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());
}
How do I make the weird text disappear?
ps, this was done in mac textedditor
I think your text file is not plain text but rather a RTF file which supports formatting. When you view it you probably use a tool which supports RTF, such as TextEdit. If you view it with less or cat you should also see the RTF markup.