Java: Make a void-method out of this class (textfile changer) - java

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 {
//...
}
}

Related

Java NullPointerException when using scanner.hasNext();

I came up with the following code to read information from a file:
import java.io.*;
import java.util.*;
public class Reader {
private Scanner s;
public void openFile() {
try {
s = new Scanner(new File("file.txt"));
} catch (Exception e) {
System.out.println("File not found. Try again.");
}
}
public void readFile() {
while (s.hasNext()) {
String a = s.next();
String b = s.next();
String c = s.next();
int d = s.nextInt();
int e = s.nextInt();
int f = s.nextInt();
}
public void closeFile() {
s.close();
}
}
However, I get a NullPointer error on the (while (s.hasNext())) line and can't find a solution.
I'm working in Eclipse and the file I'm reading from is imported correctly into the project so that should not be an issue.
EDIT:
The way I access the methods:
public class Tester {
public static void main(String[] args) {
Reader read = new Reader();
read.openFile();
read.readFile();
read.closeFile();
}
}
As per the statement where NPE throws, while (s.hasNext()), it's most probable that the s is null pointer, you can add System.out.println(s); before that statement to double confirm it.
And for the reason why the s is null, there are two possible reasons:
You didn't invoke openFile before readFile
Exception is thrown when you open the file. The s is only a declaration and hasn't pointed to any object yet.
Maybe for a better practice, you can assert whether a instance is null or not before invoking its method. And as per my understanding, the readFile depends on the result of openFile, maybe you can set return value of openFile like a boolean value and check the return value before further open file operation. It's impossible to read a file which can't be even open, right?
import java.io.*;
import java.util.*;
public class Reader {
private Scanner s;
public boolean openFile() {
try {
s = new Scanner(new File("file.txt"));
return true;
} catch (Exception e) {
System.out.println("File not found. Try again.");
return false;
}
}
public void readFile() {
while (s.hasNext()) {
String a = s.next();
String b = s.next();
String c = s.next();
int d = s.nextInt();
int e = s.nextInt();
int f = s.nextInt();
}
}
The invoker can do something like below:
Reader reader = new Reader();
if (reader.openFile())
reader.readFile();

Creating, writing to and reading files

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.

No space for a new line in parsing text from file?

I was trying to parse text from a textfile , then split it in words. However when split takes the words, it doesn't recognize a new line as a space ?
Sometimes it recognize a space on the next line but not if there are two new lines before the words continue.
I put a space on each new line to avoid it.
Is this a normal behavior, and how to avoid it ?
Using e.g a textfile with : this is a test "enter" for checking "enter-enter" something "enter" in this text (typing enter as writed)
package textparseproblem;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFileChooser;
public class TextParseProblem {
JFileChooser chooser = new JFileChooser();
File f;
String so = "";
public static void main(String[] args) throws InterruptedException, Exception {
new TextParseProblem().openFchooser();
}
private void openFchooser() throws FileNotFoundException, IOException, InterruptedException, Exception {
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
f = chooser.getSelectedFile();
} loadFile(f);
}
private void loadFile(File fileC) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
while (true) {
String s = reader.readLine();
if (s == null) break;
so += s;
}
} parseMethod();
}
private void parseMethod() {
String[] sa1 = so.split("\\s");
for(String soo : sa1) {
System.out.println(soo);
}
}
}
According to your strategy, one of the way is to add additional "space" between strings (read lines), so you can later recognize them:
private void loadFile(File fileC) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
while (true) {
String s = reader.readLine();
if (s == null) {
break;
}
so += " "+s; // here
}
}
parseMethod();
}
If in the case your string has that additional "space" you can parse it when you will correct this method:
private void parseMethod() {
String[] sa1 = so.split("\\s+"); // to recognize some spaces
for (String soo : sa1) {
System.out.println(soo);
}
}
Other methods don't need changes

Get line number from a file

How can I implement a method to return the line-number of the line currently being scanned from a file. I have two scanners, one for the file (fileScanner) and another for the line (lineScanner)
this is what I have, but I don't know if I need the linenumber in the constructor!
public TextFileScanner(String fileName) throws FileNotFoundException
{
this.fileScanner = new Scanner(new File(fileName));
this.lineScanner = new Scanner(this.fileScanner.nextLine());
this.lineNumber = 1;
}
and I need this method:
public int getLineNumber()
{
}
You can use just one Scanner object to read a file and reports the line numbers.
Here is a sample code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LineNumber {
public static void main(String [] args) throws FileNotFoundException {
System.out.printf("Test!\n");
File f = new File("test.txt");
Scanner fileScanner = new Scanner(f);
int lineNumber = 0;
while(fileScanner.hasNextLine()){
System.out.println(fileScanner.nextLine());
lineNumber++;
}
fileScanner.close();
System.out.printf("%d lines\n", lineNumber);
}
}
Now, if you want do this using an Object-Oriented Programming approach then you can do something like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileProcessor {
// Mark these field as private so the object won't get tainted from outside
private String fileName;
private File file;
/**
* Instantiates an object from the FileProcessor class
*
* #param fileName
*/
public FileProcessor(String fileName) {
this.fileName = fileName;
this.file = new File(fileName);
}
public int getLineNumbers() {
Scanner fileScanner = null;
try {
fileScanner = new Scanner(this.file);
} catch (FileNotFoundException e) {
System.out.printf("The file %s could not be found.\n",
this.file.getName());
}
int lines = 0;
while (fileScanner.hasNextLine()) {
lines++;
// Go to next line in file
fileScanner.nextLine();
}
fileScanner.close();
return lines;
}
/**
* Test our FileProcessor Class
*
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
FileProcessor fileProcessor = new FileProcessor("text.txt");
System.out.printf("%d lines\n", fileProcessor.getLineNumbers());
}
}
Prints the Current line number:
System.out.println("The line number is " + new Exception().getStackTrace()[0].getLineNumber());
Example:
public class LineNumberTest{
public static void main(String []args){
System.out.println("The line number is " + new Exception().getStackTrace()[0].getLineNumber());
}
}

How to use data stored in a variable located in a seperate file?

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;
}
}

Categories

Resources