I'm having a couple of problems setting up a system to read data into a Java program from two .data files...
I'm using Eclipse as my IDE, and have created the project in the folder where the two .data files are that I want to use. I've only just started this project, so I am still very much at its beginning...
The two .data files are: car.data and owner.data, and they are all that I have to start the project.
I've created a few classes: Owner.java, Car.java and ReadFile.java (to read the data from the .data files).
At present, my Owner.java file looks like this:
import java.io.*;
public class Owner {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ReadFile rf = new ReadFile("Owner.data");
rf.read("Owner.data");
}
File f;
public String id;
public String lastName;
public String firstName;
public String street;
public String city;
public void readOwner() throws FileNotFoundException{
//File f = new File("Smart Stream Associate Software Engineer (Java) - Bristol/assessment/src/Owner.java");
//InputStream IS = new FileInputStream(f);
}
}
My Car.java file looks like this:
public class Order {
public String orderID;
public String orderNo;
public String personID;
}
and my ReadFile.java file looks like this:
import java.io.*;
public class ReadFile {
String[] columns = new String[]{"personID", "lastName", "firstName", "street", "city"};
String[] data = new String[100];
public void read() throws IOException{
FileReader fr = new FileReader("Person.data");
BufferedReader br = new BufferedReader(fr);
String line;
int i = 0;
while((line = br.readLine())!= null){
data[i] = line;
System.out.println(data[i]);
i++;
}
br.close();
String[] dataNew = new String[i];
System.arraycopy(data, 0, dataNew, 0, i);
data = dataNew;
System.out.println("Data length: " + data.length);
}
}
Currently, when I try to run the program from the Owner.java class (as that's where the main method is), I'm getting an exception that says:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The constructor ReadFile(String) is undefined
The method read() in the type ReadFile is not applicable for the arguments (String)
The line it's complaining about is the line:
ReadFile rf = new ReadFile("Owner.data");
Could someone point out to me why I'm getting this exception, and what I've forgotten to do to avoid getting it? Many thanks in advance.
Edit 25/09/2013
So, I've tried editing my code to reflect the changes suggested by #sushain97 below, and I now have an 'Owner.java class that looks like this:
import java.io.*;
public class Person {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ReadFile rf = new ReadFile("Owner.data");
rf.read();
}
File f;
public String id;
public String lastName;
public String firstName;
public String street;
public String city;
public void readPerson() throws FileNotFoundException{
//File f = new File("Smart Stream Associate Software Engineer (Java) - Bristol/assessment/src/Person.java");
//InputStream IS = new FileInputStream(f);
}
}
and a ReadFile.java class that looks like this:
import java.io.*;
public class ReadFile {
//File file;
String[] columns = new String[]{"personID", "lastName", "firstName", "street", "city"};
String[] data = new String[100];
private File file;
public ReadFile(String fileName){
this.file = new File(fileName);
}
public void read() throws IOException{
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
int i = 0;
while((line = br.readLine())!= null){
data[i] = line;
System.out.println(data[i]);
i++;
}
br.close();
String[] dataNew = new String[i];
System.arraycopy(data, 0, dataNew, 0, i);
data = dataNew;
System.out.println("Data length: " + data.length);
}
}
However, when I run my code from the Owner.java class, I'm now getting an error that says:
Exception in thread "main" java.io.FileNotFoundException: Owner.data (The system cannot find the file specified)
and
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at ReadFile.read(ReadFile.java:15)
at Person.main(Owner.java:8)
I assume that this means that it cannot find the 'Owner.data' file- but this file is stored in the same folder as where my 'Owner.java' and 'ReadFile.java' classes are stored... any ideas why it cannot find the file, and how I can ensure that it does?
Edit 25/09/2013 # 09:45
I've edited my code to show the changes suggested by PlanetSaro in their answer, as I understand them, so I now have:
import java.io.*;
import java.util.Scanner;
public class ReadFile {
static File file;
String[] columns = new String[]{"personID", "lastName", "firstName", "street", "city"};
String[] data = new String[100];
private static void readFile(String fileName){
try{
File file = new File("Person.data");
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
public void read(File file2) throws IOException{
FileReader fr = new FileReader("Person.data");
BufferedReader br = new BufferedReader(fr);
String line;
int i = 0;
while((line = br.readLine())!= null){
data[i] = line;
System.out.println(data[i]);
i++;
}
br.close();
String[] dataNew = new String[i];
System.arraycopy(data, 0, dataNew, 0, i);
data = dataNew;
System.out.println("Data length: " + data.length);
}
}
but I'm still getting an error that says Exception in thread "main" java.io.FileNotFoundException: Owner.data (The system cannot find the file specified)
I don't understand why this is?
Edit 25/09/2013 # 10:35
Ok, so I can't seem to get this working from any of the answers that have been given so far (that may well be just because I don't fully understand the answers- I've commented on them to that effect, so if that is the case, please explain them more fully (or basically- I am a beginner).
However, I have managed to reduce the amount of errors being displayed in the console when I run the program. My two classes now look like this:
ReadFile.java:
import java.io.*;
import java.util.Scanner;
public class ReadFile {
static File file;
String[] columns = new String[]{"personID", "lastName", "firstName", "street", "city"};
String[] data = new String[100];
private static void readFile(file){
try{
File file = new File("D:\\Users\\Elgan Frost\\Desktop\\careers\\Smart Stream Associate Software Engineer (Java) - Bristol\\assessment\\srcPerson.data");
Scanner scanner = new Scanner(file1);
while(scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
public void read(File file2) throws IOException{
FileReader fr = new FileReader("D:\\Users\\Elgan Frost\\Desktop\\careers\\Smart Stream Associate Software Engineer (Java) - Bristol\\assessment\\srcPerson.data");
BufferedReader br = new BufferedReader(fr);
String line;
int i = 0;
while((line = br.readLine())!= null){
data[i] = line;
System.out.println(data[i]);
i++;
}
br.close();
String[] dataNew = new String[i];
System.arraycopy(data, 0, dataNew, 0, i);
data = dataNew;
System.out.println("Data length: " + data.length);
}
}
Person.java:
import java.io.*;
public class Person {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ReadFile rf = new ReadFile();
rf.read(ReadFile.file);
}
static File f;
public String id;
public String lastName;
public String firstName;
public String street;
public String city;
public void readPerson() throws FileNotFoundException{
//File f = new File("Smart Stream Associate Software Engineer (Java) - Bristol/assessment/src/Person.java");
//InputStream IS = new FileInputStream(f);
}
}
I am now only getting the one console error, which says:
"Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token "file", VariableDeclaratorId expected after this token
file cannot be resolved to a type"
and is complaining about line 9 in ReadFile.java, which is the line:
private static void readFile(file){
and line 7 in Person.java, which is the line:
ReadFile rf = new ReadFile();
Anyone have any ideas why this is, and how I can put it right?
It is because, the ReadFile object does not have a constructor argument with String type and also the method read() does not have any argument of type string passed in.
You need to add a overloaded constructor to your ReadFile class definition. The default constructor (which is implicit and does not require declaration) does not take any arguments however you are trying to give it one, namely a String: "Owner.data".
To fix this, you need to add a custom constructor to the ReadFile class like so:
public ReadFile(String fileName) //Constructor for a class has the same name as the Class
{
//Define the fileObject that your read method needs to access to an instance variable
this.file = new File(fileName);
}
Of course, this requires declaring the variable:
private File file;
Finally, you need to access file set in the constructor inside the read method:
FileReader fr = new FileReader(file); //file here refers to the variable set earlier
So, we end up with a slightly modified ReadFile class:
public class ReadFile {
String[] columns = new String[]{"personID", "lastName", "firstName", "street", "city"};
String[] data = new String[100];
private File file;
public ReadFile(String fileName) {
this.file = new File(fileName);
}
public void read() throws IOException {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
int i = 0;
while((line = br.readLine())!= null){
data[i] = line;
System.out.println(data[i]);
i++;
}
br.close();
String[] dataNew = new String[i];
System.arraycopy(data, 0, dataNew, 0, i);
data = dataNew;
System.out.println("Data length: " + data.length);
}
}
Finally, usage would change from rf.read("Owner.data") to rf.read().
You've not declared a ReadFile constructor that can accept a String argument. You'll need one like below. While you are at it, add a File field which you can reuse when reading.
public class ReadFile {
private File file;
public ReadFile(String file) {
this.file = new File(file);
}
...
// use the following in your read() method
// FileReader fr = new FileReader(file);
}
You can then do
ReadFile rf = new ReadFile("Owner.data"); // "Owner.data" passed as an argument
You will also get an exception on the next line
rf.read("Owner.data");
since your read() method doesn't take any arguments either.
Use the value you passed to your constructor to select the file you want to read from.
Related
I know there are many questions related to this, but I still do not follow. I have copied the below code from a tutorial on how to create, write to and read from a file. There is a CreateFile class, a ReadFile class and a Demo class:
CreateFile.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class CreateFile {
private Formatter x;
public void openFile(){
try{
x = new Formatter("chinese.txt");
}
catch(Exception e)
{
System.out.println("You have an error");
}
}
public void addRecords(){
x .format("%s%s%s", "20 ", "bucky ", "robers");
}
public void closeFile(){
x.close();
}
}
ReadFile.java
public class ReadFile {
private Scanner x;
public void openFile()
{
try{
x = new Scanner(new File("words.txt"));
}
catch(Exception e){
System.out.println("could not find file");
}
}
public void readFile()
{
while(x.hasNext())
{
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s\n", a,b,c);
}
}
public void closeFile()
{
x.close();
}
}
public class Demo {
public static void main(String[] args) {
CreateFile g = new CreateFile();
g.openFile();
g.addRecords();
g.closeFile();
WordCounter r = new WordCounter();
r.openFile();
r.readFile();
r.closeFile();
}
In Demo.java if I remove the last four statements related to reading the file, the first four statements related to opening and writing to a file run without error. However, once I add
WordCounter r = new WordCounter();
r.openFile();
r.readFile();
r.closeFile();
and run the program, it outputs: Exception in thread "main" could not find file. I am not sure what is going on, is the file chinese.txt never being created?
I'd suggest that you look into serialization it much easier and simpler than writing to .txt files.
But if you really need to do .txt files this is how you write to a .txt file
//This gets your project directory
private String projectPath = System.getProperty("user.dir");
//call save()
String save("test.txt", "This is will be save to a test.txt file");
private boolean save(String textfile String outputtext){
String filepath = projectPath + textfile;
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(filepath));
writer.write(outputtext);
writer.close();
} catch(IOException e) { }
return true;
}
And this is how you read it
private String load(String textfile){
String temp="";
String filepath = projectPath + textfile;
try{
BufferedReader reader =new BufferedReader(new FileReader(filepath));
while(true){
//this will read one line at a time you can append it output
try {
temp+= reader.readLine();
//If no more lines break out of the loop
if(line==null)
break;
}catch(IOException e){}
}
reader.close();
}
catch(IOException e){}
//Return contents of the file you loaded
return temp;
}
I hope that this code is clear enough. If you have any further questions let me know. I'll gladly answer them.
I have text files.
album.txt
new_album.txt
Each text files contains some folder name.
For example,
album.txt contains
#Event1
#Event2
#Event3
and new_album.txt contains
#Event1(update20-05-2015)
#Event2(update03-03-2016)
#Event3(update15-08-2016)
#Event4(update30-07-2017)
I want to compare similar folder name from album.txt with new_album.txt line by line, then put folder name that similar from album.txt to similar.txt and put folder name that not match to not_match.txt .
Output in similar.txt
#Event1
#Event2
#Event3
Output in not_match.txt
#Event4(update30-07-2017)
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CompareFileName {
public static void main(String[] args) throws Exception {
BufferedReader br1 = null;
BufferedReader br2 = null;
String sCurrentLine;
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
br1 = new BufferedReader(new FileReader("album.txt"));
br2 = new BufferedReader(new FileReader("new_album.txt"));
while ((sCurrentLine = br1.readLine()) != null) {
list1.add(sCurrentLine);
}
while ((sCurrentLine = br2.readLine()) != null) {
list2.add(sCurrentLine);
}
//This part is my problem
List <String> list_similar = new ArrayList<String>();
List <String> list_not_match = new ArrayList<String>();
for (String string : list1) {
if(string.matches("list2")){ //I don't know how to compare similar folder name from list2 with list1.
list_similar.add(string);
}else{list_not_match.add(string)}
}
//This part is the part I use for add string to text file but it not complete I want to write string from list_similar to similar.text and list_not_match to not_match.txt
file = new File("similar.txt");
fileName = "similar.txt";
str = file.list();
try{
PrintWriter outputStream = new PrintWriter(fileName);
for(String string:str){
outputStream.println(string);
}
outputStream.close();
System.out.println("get name complete");
}
catch (FileNotFoundException e){
e.printStackTrace();
}
System.out.println("done.");
}
If you want to read something from files, you can use these streams.
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("path\\to\\your\\file.txt"))); //or any format
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("path\\to\\your\\second\\file.txt")));
//read one line from your file
String line = reader.readLine();
//write something to your file
writer.write(line);
}
If you want to read folder names you can use this.
File f = f = new File("path\\to\\your\\folder\\with\\files");
File[] files = f.listFiles();
for(File currentFile : files) {
System.out.println(currentFile.getName());
}
If you want to create new files or folders, you can use this.
File f = f = new File("path\\to\\your\\folder\\with\\files");
f.mkdir();
//or
f.mkdirs();
//or if you have File f = new File("myTextFile.txt"); then you can create file using this:
f.createNewFile();
Application (main method)
public class Application {
public static void main(String... aArgs) throws IOException {
InputParser firstListInputParser = new InputParser(new File(/**"Your path to /album.txt"*/));
firstListInputParser.processLineByLine();
List<String> firstList = firstListInputParser.getListWithParsedFolderNames();
firstListInputParser.printMap();
InputParser secondListInputParser = new InputParser(new File(/**"Your path to /new_album.txt"*/));
secondListInputParser.processLineByLine();
List<String> secondList = secondListInputParser.getListWithParsedFolderNames();
secondListInputParser.printMap();
// Create the list with common value and write it to the file
List<String> listWithCommonValues = new ArrayList<String>(firstList);
listWithCommonValues.retainAll(secondList);
Path fileCommon = Paths.get(/**"Your path to /similar.txt"*/);
Files.write(fileCommon, listWithCommonValues, Charset.forName("UTF-8"));
// Create the list with different values and write it to the file
List<String> listWithAllValues = new ArrayList<String>(firstList);
listWithAllValues.addAll(secondList);
//remove the common values from the list with all values
listWithAllValues.removeAll(listWithCommonValues);
Path fileDistincts = Paths.get(/**"Your path to /not_match.txt"*/);
Files.write(fileDistincts, listWithAllValues, Charset.forName("UTF-8"));
}
private static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
}
Inputparser
/**
* Assumes UTF-8 encoding
*/
public class InputParser {
//create a list to hold the values
List<String> listWithParsedFolderNames = new ArrayList<>();
//private final Path fFilePath;
private final File file;
private final static Charset ENCODING = StandardCharsets.UTF_8;
/**
Constructor.
#param aFileName full name of an existing, readable file.
*/
public InputParser(File aFileName){
//fFilePath = Paths.get(aFileName);
file = aFileName;
}
/**
* Processes each line and calls {#link #processLine(String)}}.
*/
public final void processLineByLine() throws IOException {
try (Scanner fileScanner = new Scanner(file, ENCODING.name())){
while (fileScanner.hasNextLine()){
processLine(fileScanner.nextLine());
}
}
}
/**
Overridable method for processing lines in different ways.
*Parses the line and cuts away the part after '(update'
* Ex1: input line: #Event1(update20-05-2015)
* Ex1: output : #Event1
*
* Ex2: input line: #Event2
* Ex2: output : #Event2
*/
protected void processLine(String aLine){
Scanner scanner = new Scanner(aLine);
if (scanner.hasNext()) {
String name = scanner.next();
String finalName = name.split("\\(update")[0];
//stores the values in the list
listWithParsedFolderNames.add(finalName);
} else {
log("Empty or invalid line. Unable to process.");
}
}
/**
* Prints the content of the listWlistWithParsedFolderNames
*/
public void printMap() {
Iterator it = listWithParsedFolderNames.iterator();
while (it.hasNext()) {
log("The prsed value is: " + it.next());
}
}
/**
* #return the list with values
*/
public List<String > getListWithParsedFolderNames() {
return this.listWithParsedFolderNames;
}
private static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
}
In the similar.txt it will print:
#Event1
#Event2
#Event3
In the not_match.txt it will print:
#Event4
If you want it to print #Event4(update30-07-2017) into the not_match class you will have to change the list to a key value map that has the parsed input #Event4 as key and the full line #Event4(update30-07-2017) as value. After comparing the keys of the map you can write the values into your file.
I am trying to get a file to read into an Arraylist, then take the numbers read from the file and calculate the average. I am having trouble getting it to read the file and I am opening with a JFileChooser. I have spent three days trying to get this to work. I have seen some similar questions on here but none using a JFileChooser.
Here is my code for the JFileChooser. I know how to calculate the average, but I just need to read the numbers in the file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Week07 {
static JFileChooser fileChooser = new JFileChooser();
public static void main(String[] args) throws IOException {
String theFile;
theFile = getTheFileName();
double theAverage;
theAverage = getTheAverage(theFile);
displayTheResult(theAverage,"The average is: ");
}
public static String getTheFileName() {
String status;
fileChooser.showOpenDialog(null);
status = fileChooser.getSelectedFile().getAbsolutePath(); {
return status;
}
}
private static double getTheAverage(String theFile) throws NumberFormatException, IOException{
String fileName = getTheFileName();
FileReader fr = new FileReader(theFile);
BufferedReader br = new BufferedReader(fr);
so here is what i have, but now i cant get it to display the average.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Week07 {
static JFileChooser chooser = new JFileChooser();
public static void main(String[] args) throws IOException {
String theFile;
theFile = getTheFileName();
double theAverage;
//theAverage = getTheAverage(theFile);
//displayTheResult(theAverage,"The average is: ");
}
public static String getTheFileName() {
String status;
chooser.showOpenDialog(null);
status = chooser.getSelectedFile().getAbsolutePath(); {
return status;
}
}
public List<String> readFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
//check result
File theFile = chooser.getSelectedFile();
//needs exception handling etc.
BufferedReader br = new BufferedReader(new FileReader(theFile));
List<String> data = new ArrayList<String>();
String line;
while ( (line = br.readLine()) != null)
data.add(line);
br.close();
return data;
}}
public static double average(List<Integer> readFile) {
if (readFile == null || readFile.isEmpty())
return 0.0;
// Calculate the summation of the elements in the list
long sum = 0;
int n = readFile.size();
// Iterating manually is faster than using an enhanced for loop.
for (int i = 0; i < n; i++)
sum += readFile.get(i);
// We don't want to perform an integer division, so the cast is mandatory.
return ((double) sum) / n;
}
}
In Java there is the File class which is used for dealing with, well files. So whether you get the file from a FileChooser or by any other means does not matter.
There are a few things I would do differently in your getTheFileName() methode:
Return the File directly instead of the path
Creating the JFileChooser inside the methode
Check the return value of showOpenDialog (what if the user presses Cancel)
Here is some example code which reads the content of a file in a list of strings:
public List<String> readFile()
{
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
//check result
File file = chooser.getSelectedFile();
//needs exception handling etc.
BufferedReader br = new BufferedReader(new FileReader(file));
List<String> data = new ArrayList<String>();
String line;
while ( (line = br.readLine()) != null)
data.add(line);
br.close();
return data;
}
If you are using >= Java 7 you can simply use this:
List<String> data = Files.readAllLines(Path path, Charset cs);
Another way would be to use the Scanner class. This would maybe simplify things, since you can directly check and read integer/double values and sum them up.
Let's start with the proper use of the JFileChooser...
JFileChooser#showOpenDiaog returns an int
Returns: the return state of the file chooser on popdown: JFileChooser.CANCEL_OPTION
JFileChooser.APPROVE_OPTION JFileChooser.ERROR_OPTION if an error
occurs or the dialog is dismissed
This is important, as JFileChooser#getSelectedFile may also return null, which would cause your current code...
public static String getTheFileName() {
String status;
fileChooser.showOpenDialog(null);
status = fileChooser.getSelectedFile().getAbsolutePath(); {
return status;
}
}
To throw a NullPointerException...
Instead, you should consider using something like...
public static File getTheFileName() {
File file = null;
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile();
}
return file;
}
The reason for using the actual File object is it carries much more context and functionality the just a String alone.
The next step is to read the file. Depending on which version of Java you are using you could use...
File file = ...;
List<String> values = new ArrayList<String>(25);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String text = null;
while ((text = br.readLine()) != null) {
values.add(text);
}
} catch (IOException exp) {
exp.printStackTrace();
}
For Java 7 (using try-with-resources) or
File file = ...;
List<String> values = new ArrayList<String>(25);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String text = null;
while ((text = br.readLine()) != null) {
values.add(text);
}
} catch (IOException exp) {
exp.printStackTrace();
} finally {
try {
br.close();
} catch (Exception e) {
}
}
If you are using Java 6 or earlier. The important thing here is to make sure you are properly closing your resources, if you open, you must make every effort to close it.
Check out Basic I/O and How to use File Choosers for more details
What I want to do: My class copytest reads a textfile, edits one character and save this new file in a new directory. I want to program a void-method out of it, which does exactly the same and can then be used the following way:
copy(String "C:\\Old.txt", String "C:\\New.txt", int 1, int 1)
Now copy does exactly the same as my old class copytest, it reads the old file, edits it and saves it.
My first idea was to have two files as the first to arguments, but this is obviously impossible. My new idea is to give the method two strings of the wanted directories of the old and the new file. It still doesn't work. I hope, you understand, what I want to do and how to solve this problem.
Old class code (works):
import java.io.*;
import java.util.Scanner;
public class copytest {
public static void main(String[] args) throws Exception {
readFile();
}
public static void readFile() throws Exception {
// Location of file to read
File file = new File("...old.txt");
Scanner scanner = new Scanner(file);
int lineNumber=1;
int charNumber=1;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
writeFile(line);
i++;
}
scanner.close();
System.out.println("File copied.");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File("...new.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
}
New void code (first try with file as argument):
public void copy(file old, file new, int x, int y) {
public static void readFile() throws Exception {
Scanner scanner = new Scanner(old);
int lineNumber=y;
int charNumber=x;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
writeFile(line);
i++;
}
scanner.close();
System.out.println("File copied.");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File(new.getPath());
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
readFile();
}
New try with strings as argument, but still doesn't work:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class copytestnew {
public void copy(String old, String newone, int x, int y) {
// Location of file to read
File file = new File(old);
Scanner scanner = new Scanner(file);
int lineNumber=y;
int charNumber=x;
String wantedChar="r";
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber+2) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber-1) + wantedChar + line.substring(charNumber);
}
}
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file2 = new File(newone);
output = new BufferedWriter(new FileWriter(file2, true));
output.write(line);
output.write(newLine);
output.close();
i++;
}
scanner.close();
System.out.println("File copied");
}
}
I remember you! I answeared you last time on how to replace the char at one of the lines.
First, change the decleration to
public static void copy(String old, String newone, int x, int y) throws IOException {
NOTICE the throws statment!
And now when you want to call this method you should use it inside a try-catch block or declear that you throwing exception same as you did at the copy function.
public void copy(file old, file new, int x, int y) {
public static void readFile() throws Exception {
You're defining a function inside a method. As all functions in java are methods (static or non-static), this is not permitted. Try this:
class IDontKnowHowToNameIt {
public static void copy(file old, file new, int x, int y) {
//...
// call readFile from here
// ...
}
private static void readFile() throws Exception {
//...
}
}
I have two files. One file counts the number of listed events I have in a text file and stores the number of events into the variable "count". I want to then use the value in this variable to do computation in a second file. How do I do this? Do I have to create an object of the class in my first file and then reference it? I need an example please, I cannot seem to get this to work. Here is what I have tried.
My first file:
import java.util.*;
import java.io.*;
public class EventCounter {
public static void main (String [] args) throws IOException{
Scanner file = new Scanner(new File("event.txt"));
int count = 0;
while (file.hasNextLine()) {
count++;
file.nextLine();
}
System.out.println(count); //test
}
}
My Second file:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadEventFile {
private String path;
public ReadEventFile(String file) {
path = file;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
EventCounter method = new EventCounter(); //make object?
String[] dataTable = new String[count];
int i;
for (i=0; i<count; i++) { //Why count does not exist?
}
My second file does not know that count is a variable from my first file :-(
You seem to have your process flow backwards. The class with the main method will be created and run by the JVM - therefore it's your entry point.
Your ReadEventFile class therefore needs to be told the count when it is created. Simply add it to the constructor:
public static class ReadEventFile {
private final File eventFile;
private final int count;
public ReadEventFile(final int count, final File eventFile) {
this.eventFile = eventFile;
this.count = count;
}
public String[] openFile() throws IOException {
String[] dataTable = new String[count];
int i;
for (i = 0; i < count; i++) {
}
return dataTable;
}
}
Now your EventCounter needs to create a ReadEventFile instance once it knows the count and call the openFile method on it:
public static void main(String[] args) throws IOException {
final File eventFile = new File("event.txt");
int count = 0;
try (Scanner file = new Scanner(eventFile)) {
while (file.hasNextLine()) {
count++;
file.nextLine();
}
}
final ReadEventFile readEventFile = new ReadEventFile(count, eventFile);
final String[] dataTable = readEventFile.openFile();
}
The ReadEventFile does it's work and then returns the String[] back to your EventCounter.
You don't close any of your resources when you are done with them. This is asking for trouble. I have added a Java 7 try-with-resources around your Scanner in the EventCounter.
The design of this program does seem a little odd. There is no logical reason why the EventCounter should be the entry point to the application. I would recommend you create a BootStrap class that holds the main method and is the entry point that then calls both the EventCounter and the ReadEventFile.
Further, the openFile method on the ReadEventFile class isn't well named - it does more than that. Maybe processEventFile or something along those lines would be more appropriate.
your first Program
package farzi;
import java.util.*;
import java.io.*;
public class EventCounter {
public static void main (String [] args) throws IOException
{
EventCounter object = new EventCounter();
System.out.println(object.returnCount());
}
public int returnCount() throws FileNotFoundException
{
Scanner file = new Scanner(new File("event.txt"));
int count = 0;
while (file.hasNextLine()) {
count++;
file.nextLine();
}
System.out.println(count); //test
return count;
}
}
your second program
package farzi;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadEventFile
{
private String path;
public ReadEventFile(String file)
{
String path = file;
}
public String[] OpenFile() throws IOException {
EventCounter eventCounterObject = new EventCounter();
int countLocal = eventCounterObject.returnCount();
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
EventCounter method = new EventCounter(); //make object?
String[] dataTable = new String[countLocal];
int i;
String[] textData = null;
for (i=0; i<countLocal; i++) { //Why count does not exist?
textData[i] = textReader.readLine();
}
return textData;
}
}