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.
Related
So I'm new to java and I have to read strings, doubles, and integers from a file and print them out after. This is the error that java is throwing at me:
error: variable declaration not allowed here Scanner file = new
Scanner(line);
what am does it mean?
Scanner file = new Scanner(line);
Fails because a variable named file is already declared above ...
Scanner file = new Scanner(data);
Give one of the scanner variables a different name. There's some other problems with your code, but I assume this is a school assignment so only answered the question you asked.
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] splited = line.split(" ");
for (String st: splited) {
if(isInteger(st))
System.out.println("---int--->"+st);
else if(isDouble(st))
System.out.println("---dubl--->"+st);
else if (!st.isEmpty())
System.out.println("---String--->"+st);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static boolean isInteger(String st) {
try {
Integer.parseInt(st);
return true;
} catch (NumberFormatException e) {
return false;
}
}
static boolean isDouble(String str) {
try {
Float.parseFloat(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
This Maybe help you
I'm trying to read a .csv file to an array, and then parse the row on commas, to pull out specific numbers from my file. I'm not getting any errors, and the program runs fine, however it won't let me pull from anything other than thisLine[0]. There should be 3 elements in the line.
The csv looks something like this:
32.34553,-122.4535636,-118.1
32.34553,-122.4535536,-118.1
32.34553,-122.4512236,-118.1
32.34553,-122.4515466,-118.1
32.34553,-122.4532336,-118.1
When I try to call thisLine[1] (which should be something like '-122.4535636') I get :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at com.mkyong.util.ReadCSV.run(ReadCSV.java:32)
at com.mkyong.util.ReadCSV.main(ReadCSV.java:14)
I'm really new to Java so I'm sorry if this is a simple fix. Thanks for any help,
package com.mkyong.util;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadCSV {
public static void main(String[] args) {
ReadCSV obj = new ReadCSV();
obj.run();
}
public void run() {
String csvFile = "C:/Program Files/EDX/Projects/Brisbane, CA R900/Data/GIS/meters.csv";
BufferedReader br = null;
String line = "";
String csvSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) !=null) {
String[] thisLine = line.split(csvSplitBy);
System.out.println("The Current Line is: " + thisLine[0] + ", " + thisLine[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br !=null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
For my application, I need to continuously read from a file and the application will proceed on reading 100 from that file. I'm writing to the same line of the file i.e I'm overwriting the file contents. But my program reads the next line in after each iteration of the loop. My code:
public class h{
private int flag=0;
public void scan()
{
String filename="file1.txt";
try{
int i,j;
int nooflines=1;
String textData = new String();
try{
FileReader fr = new FileReader(filename);
BufferedReader textReader = new BufferedReader(fr);
while(flag==0){
textData=textReader.readLine();
if(textData==null){
Thread.sleep(3000);
continue;
}
process(textData);
}
textReader.close();
}catch(InterruptedException e){
System.out.println(e.getMessage());
}
}catch (IOException e){
System.out.println(e.getMessage());
}
}
public void process(String data){
if(data.equals("100")){
System.out.println(data);
flag=1;
}
}
}
So after one iteration my code will be scanning the second line, but the file1.txt is opened using write mode(-w) which erase its contents and writes at the beginning of the file. So how can I edit my program to keep scanning the first line of the file only?
I think this'll do it.
BufferedReader textReader;
while(flag==0){
textReader = new BufferedReader(new FileReader(filename));
textData=textReader.readLine();
if(textData==null){
Thread.sleep(3000);
continue;
}
process(textData);
}
To read your file from the beginning every 3s:
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
try(BufferedReader br = new BufferedReader(new FileReader(filename))) {
while(keepReading) {
keepReading = process(br.readLine());
}
}
}
}, 0, 3, TimeUnit.SECONDS); // every 3s
public boolean process(String data) {
// do something
return data != null && !data.equals("100");
}
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.
I am running the following code to try and read from a text file. I am fairly new to java and have been practicing by trying to create projects for myself. The following code is slightly modified from what I originally found to try and read a text file but for some reason it catching the exception every time. The text file that it is trying to read from only says "hello world". I assume it must not be finding the text file. I put it in the same folder as the source code and it appears in the source packages (I'm using netbeans btw). It probably just needs to be imported differently but I can't find any further info on it. In case my code is relevant here it is below.
package stats.practice;
import java.io.*;
import java.util.Scanner;
public final class TextCompare {
String NewString;
public static void main() {
try {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
}
System.out.println("Error");
}
}
The closing brace in the catch block is misplaced. Move it to be below the System.out.println("Error");.
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) { // <-- from here
System.out.println("Error");
// or even better
e.printStackTrace();
} // <-- to here
}
As a matter of defensive programming (pre-Java 7 at least) you should always close resources in a finally block:
public static void main(String[] args) {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {}
}
// or if you're using Google Guava, it's much cleaner:
Closeables.closeQuietly(in);
}
}
If you are using Java 7, you can take advantage of automatic resource management via try-with-resources:
public static void main(String[] args) {
try (BufferedReader in = new BufferedReader(new FileReader("hello.txt"))) {
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It isn't necessarily catching the exception every time. Your System.out.println("Error"); statement is outside of the catch block. Therefore, it is executed every time the program executes.
To fix this, move it within the braces (catch (IOException e) {System.out.println("Error");})
First step, replace below code
catch (IOException e){}
with
catch ( IOException e) { e.printStackTrace(); }
and also replace
main()
with
main(String[] args)
This will tell you the exact reason. and then you have to solve the actual reason.
Now for Netbeans, the file hello.txt has to be in your Netbeans project. like
<project_dir>
|
-->hello.txt
-->build
-->src
You have an empty catch block which is almost always a bad idea. Try putting this there:
... catch (IOException ex) {
ex.printStackTrace();
}
And you should quickly see what's going on.