I am writing a code in java to display text file in JTextArea. Can Anyone tell me what is wrong with this code. It is saying cannnot find symbol file..
FOpen.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
final JFileChooser FileDialog = new JFileChooser();
int ReturnValue=FileDialog.showOpenDialog(null);
if(ReturnValue==JFileChooser.APPROVE_OPTION)
{
File file = FileDialog.getSelectedFile();
}
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while(line!=null)
{
WritingArea.append(line+"\n");
line=in.readLine();
}
}
});
Look up 'variable scope/visibility'. Since the file attribute is declared inside the brackets, only code in that code block has access to it.
Other notes/tips:
If ReturnValue!= .. it does not make much sense to continue with the rest, so the rest of that method should also be inside the brackets.
That code will bloc the EDT for as long as it takes to load the File. Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling Thread.sleep(n) implement a Swing Timer for repeating tasks or a SwingWorker for long running tasks. See Concurrency in Swing for more details.
Please learn common Java naming conventions (specifically the case used for the names) for class, method & attribute names & use them consistently.
if WritingArea is a JTextComponent there is an easier way to load the data.
Always copy/paste error & exception output.
For better help sooner, post an SSCCE.
You really need to learn about scopes. Currently you File object is encapsulated in the if block's scope. If you want to use that File object anywhere else, it isn't allowed. So put everything into the if block, where they will be in the same scope as the File object
FOpen.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
final JFileChooser FileDialog = new JFileChooser();
int ReturnValue=FileDialog.showOpenDialog(null);
if(ReturnValue==JFileChooser.APPROVE_OPTION)
{
File file = FileDialog.getSelectedFile();
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while(line!=null)
{
WritingArea.append(line+"\n");
line=in.readLine();
}
}
}
});
Related
I am a beginner in Java, so my question would be pretty basic. Here is my problem I have a class where I process folders for query matching and indexing.I have made a GUI for the same where I will ask the user to select the directory from JFileChooser.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser f=new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
f.showOpenDialog(null);
if(f.showOpenDialog(this)==JFileChooser.APPROVE_OPTION){
}
System.out.println(f.getSelectedFile().getAbsolutePath());
}
Now I want to give this directory path to my other class so it can process the folder
obj = new object();
boolean index = false;
String str = "";
InputStreamReader r = new InputStreamReader(System.in);
obj.dataDirectory = // here should be the path of the selected folder
For Example, if a user selects c:\Desktop\TextFiles then what I want want is obj.dataDirectory=c:\Desktop\TextFiles
I tried creating an object of GUI class in this class and then tried calling that method in this class but I don`t know how to do it exactly or even if it is possible.
Thanks in Advance
I'm not exactly sure where the problem lies but the code is supposed to write the ci variable to a txt file everytime the saveCI method is called, overwriting any previous int there might or might not have been. When the loadCI method is called, whatever int value in written in the txt file needs to be saved to the ci variable and if the txt file is completely empty, ci is supposed equal 0. For some reason whenever either method is called nothing happens, the txt file always remains empty.
Here's the code:
private int ci;
private File ciFile = new File("ci.txt");
private void saveCI(){
try{
PrintWriter pw = new PrintWriter(ciFile);
pw.write(ci);
pw.close();
System.out.println("CI saved");
}catch(FileNotFoundException e){
System.out.println("CI save" + e);
}
}
public void loadCI(){
try{
Scanner sc = new Scanner(ciFile);
if(sc.hasNextInt() == false){
ci = 0;
}else{
ci = sc.nextInt();
}
System.out.println("CI loaded");
}catch(FileNotFoundException e){
System.out.println("load ci " + e);
}
}
Please keep in mind that there is more code in the class from which this sample is taken and there is another class with also alot of code in. The save and load methods are called from other methods/classes and I omitted the rest of the code because there is too much to include here. I'm trying to practice the OO methodology.
The problem is that the write(int c) method of PrintWriter interprets its argument as a character, so the zero gets written to the file as the invisible NUL character (numeric value 0) rather than the desired '0' character (numeric value 48).
Calling pw.print(ci) instead of pw.write(ci) in saveCI() should do the trick.
Source: https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html
my code,
synchronized (countInfo) {
count++;
countInfo = new File(dto.findMyLocation()+"\\Properties\\countInfo"+Start.session.getId()+".txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(countInfo));
writer.write(String.valueOf(count));
writer.close();
}
here countInfo is reference to a file and the method in which this piece of code is written my multiple threads. i am getting a null pointer exception at the "synchronized (countInfo)" line. i know this is because at this line it is not yet known wat countInfo is initialized to, so for this i will have to move the
`
countInfo = new File(dto.findMyLocation()+"\\Properties\\countInfo"+Start.session.getId()+".txt");
line outside of the synchronous block. but if i do that , then all the threads accessing this method of mine will crate a new file. But my goal is only one of the threads (the first thread to come into this method ) has to create a file and all other threads should just read the info in the created file. How can i achieve this?? Please help. I am new to java and Multi Threading! please enrich my knowledge!! thanks in advance!
UPDATE - an image that explains the flow.
the lines marked in YELLOW, cross session file access will never happen as i have used the session ID appended to the file name.
It will help you if you read a bit about threadsafe singlton or doublecheck locking mechanism.
For you scenario you can do something like this (may be for clear code seprate the logic for file creation and data writing):
//make countinfo volatile
public volatile File countInfo = null;
.
.
public void writeIntoFile(){
countInfo = getFile();
synchronized (countInfo) {
count++;
BufferedWriter writer = new BufferedWriter(new FileWriter(countInfo));
writer.write(String.valueOf(count));
writer.close();
}
}
public File getFile(){
if(countInfo==null){
synchronized (this){
if(countInfo==null){
countInfo = new File(dto.findMyLocation()+"\\Properties\\countInfo"+Start.session.getId()+".txt");
}
}
}
return countInfo;
}
I want to write data to file when it's opened, but it doesn't work. Calendar getTime works nice, System.out.println() proves this. Please, any idea, what's wrong...?
Main class:
public static void main(String[] args) throws IOException {
// TODO code application logic here
CurrentTime ct = new CurrentTime();
}
CurrentTime class:
public class CurrentTime {
public OutputStream output;
public InputStream input;
public Process npp;
CurrentTime() throws IOException
{
Timer t = new Timer();
npp = Runtime.getRuntime().exec("notepad");
output = npp.getOutputStream();
TimerTask task = new TimerTask() {
#Override
public void run()
{
String dateStr = Calendar.getInstance(new Locale("ua", "UA")).getTime().toString();
System.out.println(dateStr);
try {
output.write(dateStr.getBytes());
output.flush();
} catch (IOException ex) {
Logger.getLogger(CurrentTime.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
t.schedule(task, 1000, 2000);
}
}
Maybe this code is wrong in all, np. In this way, I want to discover this moment by any side, is it impossible at all?
UPDATE: it's not actual anymore but just for a note, that time I was trying to implement some kind of tailing operation to the text editor directly and now I understand how abnormal this idea was.. had to be implemented using totally other way of course.
Interesting:
Lets deal this in simple way.
1. Save a file test.txt somewhere.
2. Open that file and keep it opened
In Java write to this file (Standard Code)
FileWriter fw = new FileWriter(new FileOutputStream(new File("c:/test.txt")));
fw.write("ABC")
Now go to notepad file again. I normally used Textpad it does refresh automatically (by an alert) because we changed it behind the scene (In your case through Java).
I hope that will clarify a bit.
To be fare trying to excess the genric notepad exe doesn't gurrantee which file you will write in. I am not sure how windows deal with it because you can open 3 different files at one time and which one you will expect to have your data written through java???
You're doing it wrong - It's impossible. notepad absolutely ignores it's input while it's running (like most GUI-programs). If you want to show a textbox and write text in it, simply create one with Swing/SWT/...
If you just want to write into a file, just create a new PrintWriter and use it to write files: http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html
You shouldn't try to write through Notepad. Check out PrintWriter.
I am new to java.
I have a project from college where I have to make entries to txt file through 2 JTextField boxes and 1 JButton (save) which will display the entries in JTextArea. I am able to make entries in txt file successfully. But how to refresh JTextArea at run-time to display the new entries I recently made?
Thanks for helps:
below is my code:
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader("RokFile.txt"));
try {
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
jTextArea1.append(line+"\n");
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
Let me know if its correct?
Thanks
JTextArea.append ought to suffice. This method is thread-safe and will update the text area's content automatically.
This answer assumes that you already have the EventListeners configured.
You can use two methods,
If you want to display the content as soon as you write in jTextField(fairly attainable), you can do it this way, in the FocusLost event of jTextField, give something like jTextArea.setText(jTextField.getText())
Note, that this is fairly near to what you want.(also,NOT perfect code)
If you want to display the contents when you click save , the above code, jTextArea.setText(jTextField.getText()) may be given in the event handler of the save button.