Scanner doesn't read from file - java

I'm writing program, which will be read file, choose by user. I have code:
public class program extends javax.swing.JFrame {
private String textEncode;
...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fch = new JFileChooser();
int choose = fch.showOpenDialog(this);
if(choose == JFileChooser.APPROVE_OPTION) {
String help = fch.getSelectedFile().getPath();
jTextField2.setText(help);
try {
Scanner in = new Scanner(new File(help));
while(in.hasNextLine()) {
textEncode = in.nextLine();
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Nie znaleziono pliku", "Błąd wczytywania", JOptionPane.ERROR_MESSAGE);
}
}
jTextArea1.setText(textEncode);
System.out.println(textEncode);
}
My file has 1 line of text. When program end read file, variable textEncode has value "null". Where is problem?
I try with in.next() and in.hasNext(), but it doesn't work too.

I found a solution:
public class program extends javax.swing.JFrame {
private String textEncode;
...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fch = new JFileChooser();
int choose = fch.showOpenDialog(this);
if(choose == JFileChooser.APPROVE_OPTION) {
String help = fch.getSelectedFile().getPath();
jTextField2.setText(help);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(help), "UTF-8"));
String line;
String readed = "";
while((line = in.readLine()) != null) {
readed = readed + line + "\n";
}
jTextArea1.setText(readed);
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Nie znaleziono pliku", "Błąd wczytywania", JOptionPane.ERROR_MESSAGE);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(aes.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(aes.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
But now I have problem with display jTextArea1. When file has loaded, the textArea is resize and looks like this: application window
TextArea is added into jScrollPane.

I had the same problem, and it took me a while to figure it out.
My problem was that my file contained french special characters like "é".
This caused the scanner to return "null" for scanner.nextLine() without causing any exception, no matter how long was the file, no matter where the special characters were placed.
To solve this, I just removed all the special characters. If anybody has a solution to make Scanner read the special characters, he's welcome to comment below.

Related

Buffered reader causing an infinite loop

I'm currently doing a test project to understand how to read/write into a text file. This is my code:
package testings;
import java.util.Scanner;
import java.io.*;
public class Writing_Reading_files {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
File testFile = new File("testFile.dat");
String test, sName;
try{
PrintWriter print = new PrintWriter(new BufferedWriter(new FileWriter(testFile)));
test = in.nextLine();
print.println(test);
print.close();
}catch(IOException e) {
System.out.println("IO exception");
System.exit(0);
}
try {
BufferedReader readerName = new BufferedReader(new FileReader(testFile));
while(readerName != null) {
sName = readerName.readLine();
System.out.println(sName);
}
readerName.close();
} catch(FileNotFoundException e) {
System.out.println("FileNotFound");
System.exit(0);
} catch(IOException e) {
System.out.println("IO exception");
System.exit(0);
}
}
}
The while loop results in spitting out the line I put then nulls for an infinite loop if I try While(readerName.readLine != null) it stops the infinite loop but only outputs a null and I don't know where to go from there, I've tried following a youtube tutorial but he has it the same as my code so I'm unsure why I'm null keeps repeating. Thanks in advance for any help.
why would readerName become null? Maybe you mean that the String returned by readLine is null?
Consider
BufferedReader readerName = new BufferedReader(new FileReader(testFile));
String sName = readerName.readLine();
while(sName != null) {
System.out.println(sName);
sName = readerName.readLine();
}
Also consider using try-with-resources when opening your file.

Using parsed input from text file as parameter for new Event

I've working on an assignment that asks me to alter a method in a class to take content from a textfile and use it to create multiple instances of various subclasses of the Event Class. Here is the text file:
Event=ThermostatNight,time=0
Event=LightOn,time=2000
Event=WaterOff,time=8000
Event=ThermostatDay,time=10000
Event=Bell,time=9000
Event=WaterOn,time=6000
Event=LightOff,time=4000
Event=Terminate,time=12000
The Event=* is the name of the subclass, while time=* is a parameter that is used in the subclass' constructor. The Event class itself is an abstract class and is used for inheritance.
public class Restart extends Event {
Class eventClass;
String eventInput;
Long timeDelay;
public Restart(long delayTime, String filename) {
super(delayTime);
eventsFile = filename;
}
public void action() {
List<String> examples = Arrays.asList("examples1.txt", "examples2.txt", "examples3.txt", "examples4.txt");
for (String example : examples) {
//finding pattern using Regex
Pattern pattern = Pattern.compile(example);
Matcher matcher1 = pattern.matcher(eventsFile);
if (matcher1.find()) {
File file = new File(example);
String line;
try {
FileReader fileReader = new FileReader(file);
Scanner sc = new Scanner(file);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
sc.useDelimiter("\n");
//Parsing through text
while (sc.hasNext()) {
String s = sc.next();
String[] array1 = s.split(",");
String[] array2 = array1[0].split("=");
eventInput = array2[1];
String[] array3 = array1[1].split("=");
String timeInput = array3[1];
try {
eventClass = Class.forName(eventInput);
timeDelay = Long.parseLong(timeInput);
try {
addEvent(new eventClass(timeDelay));
}
//catch block
catch(NoSuchMethodException e){
System.out.println("No Such Method Error");
} catch (Exception e) {
System.out.println("error");
}
//catch block
} catch (ClassNotFoundException ex) {
System.out.println("Unable to locate Class");
} catch (IllegalAccessException ex) {
System.out.println("Illegal Acces Exception");
} catch (InstantiationException ex) {
System.out.println("Instantiation Exception");
}
}
}
//Close bufferedReader
bufferedReader.close();
}
//catch block
catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
file + "'");
} catch (IOException ex) {
ex.printStackTrace();
}
break;
}
//if input match is not found
else {
System.out.println("No Match Found");}
}
}
I seem to be able to parse fine, and find the strings i'm looking for, but I'm not able to use eventInput which I've pulled from the text file as a parameter to create a new event.
eventClass = Class.forName(eventInput);
doesn't seem to be turning my string into an acceptable parameter either.
Any help would be much appreciated!
I know I'm probably missing something key here, but I've been staring at it too long that it seems like a lost cause.
Here is the Event class:
public abstract class Event {
private long eventTime;
protected final long delayTime;
public Event(long delayTime) {
this.delayTime = delayTime;
start();
}
public void start() { // Allows restarting
eventTime = System.currentTimeMillis() + delayTime;
}
public boolean ready() {
return System.currentTimeMillis() >= eventTime;
}
public abstract void action();
} ///:~
I think you've misunderstood how reflection works. Once you have a Class object (the output from Class.forName(), you have to find the appropriate constructor with
Constructor<T> constructor = eventClass.getConstructor(parameter types)
and then create a new instance with
constructor.newInstance(parameters);
For a no-arg constructor there's a shortcut
eventClass.newInstance();
I strongly suggest you read the tutorials on reflection before proceeding.

How to monitor a text file in java

I am making an application that will display a gui and read a text file. When the contents of the text file changes it will execute changes to the gui. However i need the gui to constantly be reading and checking the textfile for changes. I have tried thread.sleep() which just takes control and no code works other than the loop. After looking around i found reference to swing timers and running in new threads that weren't the EDT. This stuff is lost on me and I can find no way to implement it. Any help would be appreciated.
public void run() {
initComponents();
while(true){System.out.println("ok");
try {
try {
File myFile = new File("C:\\Users\\kyleg\\OneDrive\\Documents\\123.txt");
System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());
Scanner input = new Scanner(myFile);
String in = "";
in = input.nextLine();
System.out.println(in);
switch(in){
case("1"):
break;
case("2"):
break;
case("3"):
break;
}
} catch (IOException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This is just a simple code for file monitoring, hope it can help you.
File f = new File("Path_to_the_file");
new Thread(new Runnable() {
#Override
public void run() {
long l = f.lastModified();
String s = "";
while (true) {
if (f.lastModified() == l) {
System.out.print();
} else {
try {
Scanner sc = new Scanner(f);
s = "";
while (sc.hasNext()) {
s += sc.nextLine();
s += "\n";
jTextArea1.setText(s);
}
System.out.println(false);
l = f.lastModified();
sc.close();
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
}
}
}
}).start();

Linux terminal Output to JTextpane

I am currently looking for ways that I could actually print information to the jTextpane when I run the following code. When I press the button to run it, the program actually hang and no display for the output. Is there anyway to go round it or to fix it?
private void ScannetworkActionPerformed(java.awt.event.ActionEvent evt) {
Process p = null;
try {
p = Runtime.getRuntime().exec("ipconfig /all");
} catch (IOException ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
try {
p.waitFor();
} catch (InterruptedException ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader buf = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
String output = "";
try {
while ((line = buf.readLine()) != null) {
output += line + "\n";
} } catch (IOException ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
nninfo.setText(output);
Screenshot:
You will need to execute the process in a separate thread, otherwise it will be executed in the UI-Thread and will block any refresh events as long as the process is running. In swing this is usually done by using a SwingWorker (just google for it and you'll probably find some nice tutorials).
Furthermore Process.waitFor() will wait for the process to finish and after that you'll read the contents of the process' output. That is you'll not get any updates as long as the process is running. To update your UI with information from the running process you have to read the data from the process' input stream prior to waiting for the process to finish. Maybe this question and the accepted answer will help you to figure out how to do this.
This is what your SwingWorker might look like. I haven't tested it, but it should give you some idea:
public class ScannetworkWorker
extends SwingWorker<String, String>
{
private final JTextPane mOutputPane;
public ScannetworkWorker(JTextPane aOutputPane)
{
super();
mOutputPane = aOutputPane;
}
#Override
protected String doInBackground() throws Exception
{
Process p = null;
try
{
p = Runtime.getRuntime().exec("ipconfig /all");
}
catch (IOException ex)
{
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
String output = "";
try
{
while ((line = buf.readLine()) != null)
{
publish(line);
output += line + "\n";
}
}
catch (IOException ex)
{
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
p.waitFor();
}
catch (InterruptedException ex)
{
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
return output;
}
#Override
protected void process(List<String> aChunks)
{
final String intermediateOutput = aChunks.stream().collect(Collectors.joining("\n"));
final String existingText = mOutputPane.getText();
final String newText = existingText + "\n" + intermediateOutput;
mOutputPane.setText(newText);
}
}

can i make my app (open with) windows menu with java (need examples)

i need some example to make my app as default text editor in java
(i mean when I open the text file opens with my program)
How can I do that with Java ??
I finally found the answer after many tests When i open the text file with my app from open with menu in windows
public static void main(String[] args) {
FileReader file_reader = null;
try {
new Notepad().setVisible(true);
file_reader = new FileReader(args[0]);
BufferedReader br = new BufferedReader(file_reader);
String temp = "";
while (br.ready())
{
int c = br.read();
temp = temp+ (char)c;
}
myarea.setText(temp);
br.close();
file_reader.close();
textContent = myarea.getText();
} catch (FileNotFoundException ex) {
Logger.getLogger(Notepad.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Notepad.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
you must make your app exe

Categories

Resources