Printing a .txt on the screen - java

I'm trying to print a .txt on the screen.I have a menu with different options and I don't know why it fails. The file directory should be defined by the string FITXER. I only want to print the text file, I don't need to save the content. The bug is on the BufferedReader and FileReader arxiu, it's the name of the file variable that gets the value of FITXER.
import java.util.Scanner;
import java.io.*;
public class Copiador {
Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
Copiador programa = new Copiador();
programa.inici();
}
public void inici() throws IOException {
int opcio;
do {
System.out.println("Llegir (1)");
System.out.println("Copiar (2)");
System.out.println("Surtir (3)");
opcio = sc.nextInt();
switch (opcio) {
case 1:
Llegir();
break;
case 2:
System.out.println("Skipped Consultar");
//Consultar(nomusuaris);
break;
}
} while (opcio != 3);
sc.close();
}
public void Llegir() throws IOException {
String FITXER;
File arxiu = null;
FileReader fr = null;
BufferedReader br = null;
System.out.println("Que vols llegir?");
FITXER = sc.nextLine();
arxiu = new File(FITXER);
fr = new FileReader(arxiu);
br = new BufferedReader(fr);
String linea;
while ((linea = br.readLine()) != null)
System.out.println(linea);
System.out.println("Confirmat");
fr.close();
}
}

Related

Reaching command line arguments in another class

A have four classes: Main, Read, Author, Commands.
In Read class:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class Read {
static ArrayList<String> arAuthor = new ArrayList<>();
static ArrayList<String> arCommand = new ArrayList<>();
public static ArrayList<String> getArAuthor() {
return arAuthor;
}
public static void setArAuthor(ArrayList<String> arAuthor) {
Read.arAuthor = arAuthor;
}
public static ArrayList<String> getArCommand() {
return arCommand;
}
public static void setArCommand(ArrayList<String> arCommand) {
Read.arCommand = arCommand;
}
public static void main(String[] args) {
BufferedReader author;
BufferedReader command;
String thisLine;
String thisLine1;
try {
author = new BufferedReader(new FileReader(args[0]));
command = new BufferedReader(new FileReader(args[1]));
while ((thisLine = author.readLine()) != null) {
System.out.println(thisLine);
arAuthor.add(thisLine);
}
while ((thisLine1 = command.readLine()) != null) {
System.out.println(thisLine1);
arCommand.add(thisLine1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
My code works as Read.java args[0] args[1] but i want it to work like Main.java args[0] args[1]. I am new to Java so ı can't figure how can i pass this arguments to Main.java
Solution:
public class Reader {
public List<String> arAuthor = new ArrayList<>();
public List<String> arCommand = new ArrayList<>();
public void read(String first, String second) throws IOException {
String thisLine;
String thisLine1;
try (BufferedReader author = new BufferedReader(new FileReader(first));
BufferedReader command = new BufferedReader(new FileReader(second));){
while ((thisLine = author.readLine()) != null) {
System.out.println(thisLine);
arAuthor.add(thisLine);
}
while ((thisLine1 = command.readLine()) != null) {
System.out.println(thisLine1);
arCommand.add(thisLine1);
}
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
Reader reader = new Reader();
reader.read(args[0], args[1]);
System.out.println(reader.arAuthor);
System.out.println(reader.arCommand);
}
}

FileWriter method doesn't print anything unless append is true

Newbie here. My goal is to read a txt file, eliminate characters ("-" and " "), and replace the existing text with the new cleaned up text.
example: 855-555-1234 >> 8555551234.
I'm stuck on my append boolean. I'm using the guides here and here.
When my append is true then I get the text that I want at the end of the file, but when it is false, the file is completely blank.
My main method looks like:
public class Main {
public static void main(String[] args) throws IOException{
String file_name = "C:/TollFreeToPort.txt";
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
WriteFile data = new WriteFile(file_name, true);
int i;
for (i = 0; i < aryLines.length; i++) {
System.out.println(aryLines[i]);
data.writeToFile(aryLines[i]);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
My ReadFile Class:
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine()
.replace("-", "")
.replace(" ", "");
}
textReader.close();
return textData;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
My WriteFile Class:
package textfiles;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class WriteFile {
private String path;
private boolean append_to_file = false;
public WriteFile(String file_path) {
path = file_path;
}
public WriteFile(String file_path, boolean append_value) {
path = file_path;
append_to_file = append_value;
}
public void writeToFile (String textLine) throws IOException{
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textLine);
print_line.close();
}
}

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

How can I take rows to the TXT file in the method?

How can I print the line in the txt file drawn in the void txt() method, inside the driver.get() parentheses in void link() with quotes?
I want to get a link from the txt file and let the automatic program enter the site.
Thanks for your help.
package test2;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class test2 {
public WebDriver driver = new ChromeDriver();
public Actions action = new Actions(driver);
public static String rows = "";
public void link() throws InterruptedException {
// driver.get("https://www.google.com/");
//How can I type here,taken row from the TXT file in the quotes("")?
driver.get(rows);
Thread.sleep(3000);
}
public void txt() throws IOException {
// open the LinkAl txt file
File file = new File("LinkAl.txt");
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(file));
int i=0;
rows = reader.readLine();
while (rows!=null) {
i++;
// Get the second row to the LinkAl txt file
if(i==2)
{
System.out.println(rows);
}
rows = reader.readLine();
}
}
public void driverquit() {
driver.quit();
}
public static void main(String[] args) throws InterruptedException, IOException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
test2 Links = new test2();
// Links.link();
Links.txt();
Links.driverquit();
}
}
Change your below method like mentioned to read file line by line till EOF.
public void txt() throws IOException {
// open the LinkAl txt file
File file = new File("LinkAl.txt");
String line="";
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
// System.out.println(line);
link(line);
}
}
Also if you want to pass the read line to link method change it as below
public void link(String line) throws InterruptedException {
System.out.println("Dosyadançekilenlerveriler: " + line);
// driver.get("https://www.google.com/");
driver.get(line);
Thread.sleep(3000);
}

Java- reading from .data files

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.

Categories

Resources