Reaching command line arguments in another class - java

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

Related

I'm trying to read a text file and store it in an arraylist of objects

I'm trying to read a text file and store it in an arraylist of objects, but I keep getting an error saying I cannot convert a String to an Item, which is type of arraylist I am using. I have tried various solutions, but am not quite sure how its is suppossed to be done. I am new to coding and have this assignment due soon. Anything helps!
private void loadFile(String FileName)
{
Scanner in;
Item line;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
line = in.nextLine();
MyStore.add(line);
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
my apologies for not adding the Item class
public class Item
{
private int myId;
private int myInv;
//default constructor
public Item()
{
myId = 0;
myInv = 0;
}
//"normal" constructor
public Item(int id, int inv)
{
myId = id;
myInv = inv;
}
//copy constructor
public Item(Item OtherItem)
{
myId = OtherItem.getId();
myInv = OtherItem.getInv();
}
public int getId()
{
return myId;
}
public int getInv()
{
return myInv;
}
public int compareTo(Item Other)
{
int compare = 0;
if (myId > Other.getId())
{
compare = 1;
}
else if (myId < Other.getId())
{
compare = -1;
}
return compare;
}
public boolean equals(Item Other)
{
boolean equal = false;
if (myId == Other.getId())
{
equal = true;;
}
return equal;
}
public String toString()
{
String Result;
Result = String.format("%8d%8d", myId, myInv);
return Result;
}
}
This is the creation of my arraylist.
private ArrayList MyStore = new ArrayList ();
Here is a sample of my text file.
3679 87
196 60
12490 12
18618 14
2370 65
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.rosmery;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*
* #author Sem-6-INGENIERIAINDU
*/
public class aaa {
public static void main(String arg[]) throws FileNotFoundException, IOException{
BufferedReader files=new BufferedReader(new FileReader(new File("")));
List<String> dto=new ArrayList<>();
String line;
while((line= files.readLine())!= null){
line= files.readLine();
dto.add(line);
//Hacer la logica para esos datos
}
}
}
in.nextLine() returns a String.
So, you cannot assign in.nextLine() to an instance of Item.
Your code may need to correct it as:
List<String> myStore = new ArrayList<String>();
private void loadFile(String FileName)
{
Scanner in;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
myStore.add(in.nextLine());
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
If you want to have a list of Item after reading a file, then you need provide the logic that convert given line of information into an instance of Item.
let's say your file content is in the following format.
id1,inv1
id2,inv2
.
.
Then, you can use the type Item as the following.
List<Item> myStore = new ArrayList<Item>();
private void loadFile(String FileName)
{
Scanner in;
String[] line;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
line = in.nextLine().split(",");
myStore.add(new Item(line[0], line[1]));
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
One of the possible solutions (assuming that the data in file lines is separated by a comma), with using streams:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
List<Item> items = loadFile("myfile.txt");
System.out.println(items);
}
private static List<Item> loadFile(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream
.map(s -> Stream.of(s.split(",")).mapToInt(Integer::parseInt).toArray())
.map(i -> new Item(i[0], i[1]))
.collect(Collectors.toList());
}
}
}
or with foreach:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
List<Item> items = new ArrayList<>();
for (String line : loadFile("myfile.txt")) {
String[] data = line.split(",");
int id = Integer.parseInt(data[0]);
int inv = Integer.parseInt(data[1]);
items.add(new Item(id, inv));
}
System.out.println(items);
}
private static List<String> loadFile(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream.collect(Collectors.toList());
}
}
}

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

String line or StringTokenizer with a Reader?

I had a file to read and with this code I succeeded my JUnit tests. As you can see, I pass the String line as parameter to the readPrevisione(...) method.
package oroscopo.persistence;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import oroscopo.model.Previsione;
import oroscopo.model.SegnoZodiacale;
public class TextFileOroscopoRepository implements OroscopoRepository {
private HashMap<String, List<Previsione>> mapSettore = new HashMap<>();
public TextFileOroscopoRepository(Reader baseReader) throws IOException, BadFileFormatException{
if (baseReader == null)
throw new IllegalArgumentException("baseReader is null");
BufferedReader bufReader = new BufferedReader(baseReader);
String line;
while((line=bufReader.readLine()) != null){
readPrevisione(line,bufReader);
}
}
private void readPrevisione(String line, BufferedReader bufReader) throws IOException, BadFileFormatException{
String nomeSettore = line.trim();
if (!Character.isUpperCase(nomeSettore.charAt(0)))
throw new BadFileFormatException();
List<Previsione> listaPrev = new ArrayList<>();
while (!(line = bufReader.readLine()).equalsIgnoreCase("FINE")){
try{
StringTokenizer st1 = new StringTokenizer(line, "\t");
if(st1.countTokens() < 2)
throw new BadFileFormatException();
String prev = st1.nextToken("\t").trim();
int val = Integer.parseInt(st1.nextToken("\t").trim());
Set<SegnoZodiacale> segni = new HashSet<>();
if (st1.hasMoreTokens()){
while(st1.hasMoreTokens()){
try{
segni.add(SegnoZodiacale.valueOf(st1.nextToken(",").trim()));
}
catch (IllegalArgumentException e){
throw new BadFileFormatException();
}
}
Previsione p = new Previsione(prev,val,segni);
listaPrev.add(p);
}
else{
Previsione p2 = new Previsione(prev,val);
listaPrev.add(p2);
}
}
catch (NumberFormatException e){
throw new BadFileFormatException();
}
catch (NoSuchElementException e){
throw new BadFileFormatException();
}
}
mapSettore.put(nomeSettore, listaPrev);
}
#Override
public Set<String> getSettori() {
return mapSettore.keySet();
}
#Override
public List<Previsione> getPrevisioni(String settore) {
return mapSettore.get(settore.toUpperCase());
}
}
Here with the same code, instead passing the read line as parameter, I pass the StringTokenizer that already has read the line. It should work like above but my JUnit tests fail. What did I do wrong?
package oroscopo.persistence;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import oroscopo.model.Previsione;
import oroscopo.model.SegnoZodiacale;
public class TextFileOroscopoRepository implements OroscopoRepository {
private HashMap<String, List<Previsione>> mapSettore = new HashMap<>();
public TextFileOroscopoRepository(Reader baseReader) throws IOException, BadFileFormatException{
if (baseReader == null)
throw new IllegalArgumentException("baseReader is null");
BufferedReader bufReader = new BufferedReader(baseReader);
String line;
while((line=bufReader.readLine()) != null){
StringTokenizer st = new StringTokenizer(line);
readPrevisione(st,bufReader);
}
}
private void readPrevisione(StringTokenizer st, BufferedReader bufReader) throws IOException, BadFileFormatException{
String nomeSettore = st.nextToken().trim();
if (!Character.isUpperCase(nomeSettore.charAt(0)))
throw new BadFileFormatException();
List<Previsione> listaPrev = new ArrayList<>();
String line;
while (!(line = bufReader.readLine()).equalsIgnoreCase("FINE")){
try{
StringTokenizer st1 = new StringTokenizer(line, "\t");
if(st1.countTokens() < 2)
throw new BadFileFormatException();
String prev = st1.nextToken("\t").trim();
int val = Integer.parseInt(st1.nextToken("\t").trim());
Set<SegnoZodiacale> segni = new HashSet<>();
if (st1.hasMoreTokens()){
while(st1.hasMoreTokens()){
try{
segni.add(SegnoZodiacale.valueOf(st1.nextToken(",").trim()));
}
catch (IllegalArgumentException e){
throw new BadFileFormatException();
}
}
Previsione p = new Previsione(prev,val,segni);
listaPrev.add(p);
}
else{
Previsione p2 = new Previsione(prev,val);
listaPrev.add(p2);
}
}
catch (NumberFormatException e){
throw new BadFileFormatException();
}
catch (NoSuchElementException e){
throw new BadFileFormatException();
}
}
mapSettore.put(nomeSettore, listaPrev);
}
#Override
public Set<String> getSettori() {
return mapSettore.keySet();
}
#Override
public List<Previsione> getPrevisioni(String settore) {
return mapSettore.get(settore.toUpperCase());
}
}
EDIT: Here is the File.txt that I want to read.
And here is an example of one of my JUnit test:
#Test
public void testLetturaCorrettaPrevisioni1() throws IOException, BadFileFormatException {
Reader mr = new StringReader(
"NOMESEZIONE\navrai la testa un po' altrove\t\t4\tARIETE,TORO,GEMELLI\ngrande intimita'\t9\nFINE\n"
+ "SEZIONE2\ntesto di prova\t\t\t\t\t66\t\nFINE");
OroscopoRepository or = new TextFileOroscopoRepository(mr);
assertEquals("avrai la testa un po' altrove", or.getPrevisioni("nomesezione").get(0).getPrevisione());
assertEquals(4, or.getPrevisioni("nomesezione").get(0).getValore());
Set<SegnoZodiacale> validi = new HashSet<SegnoZodiacale>() {
private static final long serialVersionUID = 1L;
{
add(SegnoZodiacale.ARIETE);
add(SegnoZodiacale.TORO);
add(SegnoZodiacale.GEMELLI);
}
};
for (SegnoZodiacale s : SegnoZodiacale.values()) {
if (validi.contains(s))
assertTrue(or.getPrevisioni("nomesezione").get(0).validaPerSegno(s));
else
assertFalse(or.getPrevisioni("nomesezione").get(0).validaPerSegno(s));
}
assertEquals("grande intimita'", or.getPrevisioni("nomesezione").get(1).getPrevisione());
assertEquals(9, or.getPrevisioni("nomesezione").get(1).getValore());
for (SegnoZodiacale s : SegnoZodiacale.values()) {
assertTrue(or.getPrevisioni("nomesezione").get(1).validaPerSegno(s));
}
}
You are creating StringTokenizer with default delimiter, that is, "the space character, the tab character, the newline character, the carriage-return character, and the form-feed character."
So in the first case you set as value of the "nomeSettore" variable the whole line but when you use StringTokenizer.nextToken() you are giving to "nomeSettore" just the value of the first token. So, "nomeSettore" can have different values if your String "line" contains whitespaces and you will have different key-value pairs inside you map.
You can take a look at this example:
public class TestSO {
public static void main(String[] args) {
String line = "abcdfs faf afd fa";
StringTokenizer st = new StringTokenizer(line);
readPrevisione(st, null);
readPrevisione(line, null);
}
private static void readPrevisione(StringTokenizer st, BufferedReader bufReader) {
String nomeSettore = st.nextToken().trim();
System.out.println(nomeSettore);
}
private static void readPrevisione(String st, BufferedReader bufReader) {
String nomeSettore = st.trim();
System.out.println(nomeSettore);
}
}
It prints as output:
abcdfs
abcdfs faf afd fa
I've understood why it didn't work..
The String line was : "EXAMPLE\n"
but after
while((line=bufReader.readLine()) != null){
...}
line = "EXAMPLE" because the readLine() eats the newline.
So I passed to the readPrevisione() a StringTokenizer as parameter
while((line=bufReader.readLine()) != null){
StringTokenizer st = new StringTokenizer(line);
readPrevisione(st,bufReader);
}
private void readPrevisione(StringTokenizer st, BufferedReader bufReader) throws IOException, BadFileFormatException{
String nomeSettore = st.nextToken().trim();
...}
And st.nextToken() search for a \n that is not contained in "EXAMPLE". That's why it didn't work.

Java ProcessBuilder Output to String

How to redirect or get the system output to String?
ProcessBuilder pb = new ProcessBuilder().inheritIO();
...
for (...){
pb.command(...);
pb.start();
//here >>> assign output string to variable
}
Here is an opinion on how to capture the standard output of a system command process into a string container.
Adapted from the web:
try {
ProcessBuilder pb = new ProcessBuilder("echo", "dummy io");
final Process p=pb.start();
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!=null) sb.append(line);
}
System.out.println(sb.toString());
In congruence with my original comment on what would be a good example of Basic I/O. I hacked out some code, with a few more features than basic.
Extras
An environment shell for variables and
A working directory
These features add "profile-style" execution to your System commands.
Foundational Work
Java Threading and Joining by Oracle.
Code
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**
* Created by triston on 11/2/17.
*/
public class Commander {
private Commander(){} // no construction
public static class StreamHandler implements Runnable {
Object source;
Object destination;
StreamHandler(Object source, Object oDestination) {
this.source = source; this.destination = oDestination;
}
public void run() {
if (source instanceof InputStream) {
BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) source));
String line;
try {
while ((line = br.readLine()) != null) ((StringBuilder) destination).append(line + '\n');
} catch (IOException oE) {
}
} else {
PrintWriter pw = new PrintWriter((OutputStream)destination);
pw.print((String)source);
pw.flush(); pw.close();
}
}
public static Thread read(InputStream source, StringBuilder dest) {
Thread thread = new Thread(new StreamHandler(source, dest));
(thread).start();
return thread;
}
public static Thread write(String source, OutputStream dest) {
Thread thread = new Thread(new StreamHandler(source, dest));
(thread).start();
return thread;
}
}
static Map<String, String> environment = loadEnvironment();
static String workingDirectory = ".";
static Map<String, String> loadEnvironment() {
ProcessBuilder x = new ProcessBuilder();
return x.environment();
}
static public void resetEnvironment() {
environment = loadEnvironment();
workingDirectory = ".";
}
static public void loadEnvirons(HashMap input) {
environment.putAll(input);
}
static public String getEnviron(String name) {
return environment.get(name);
}
static public void setEnviron(String name, String value) {
environment.put(name, value);
}
static public boolean clearEnviron(String name) {
return environment.remove(name) != null;
}
static public boolean setWorkingDirectory(String path) {
File test = new File(path);
if (!test.isDirectory()) return false;
workingDirectory = path;
return true;
}
static public String getWorkingDirectory() {
return workingDirectory;
}
static public class Command {
ProcessBuilder processBuilder = new ProcessBuilder();
Process process;
public Command(String... parameters) {
processBuilder.environment().putAll(environment);
processBuilder.directory(new File(workingDirectory));
processBuilder.command(parameters);
}
public int start(String input, StringBuilder output, StringBuilder error) throws IOException {
// start the process
process = processBuilder.start();
// start the error reader
Thread errorBranch = StreamHandler.read(process.getErrorStream(), error);
// start the output reader
Thread outputBranch = StreamHandler.read(process.getInputStream(), output);
// start the input
Thread inputBranch = StreamHandler.write(input, process.getOutputStream());
int rValue = 254;
try {
inputBranch.join(); rValue--;
outputBranch.join(); rValue--;
errorBranch.join(); rValue--;
return process.waitFor();
} catch (InterruptedException oE) {
oE.printStackTrace();
return rValue;
}
}
}
Testing
#Test public void foo() {
Command cmd = new Command("sh", "--");
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
int pValue = 127;
try {
pValue = cmd.start("echo well done > /dev/stderr\n\necho oh, wow; false", output, error);
} catch (IOException oE) {
}
System.out.println("output: "+output.toString());
System.out.println("error: "+error.toString());
System.out.println("\nExit code: "+pValue);
System.exit(pValue);
}
Bring your own package and JUnit annotations. This sample code demonstrates return value, command input, command standard output, and command error output.
My original design, called for the main thread to perform the standard output processing.
Have a great day.

FileNotFound exception while files already exist

this code couldn't find the files that the buffered reader is supposed to read from it and i have the files in the src folder in eclipse project and it still doesn't read from file so does anybody have any idea about what the problem is.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.*;
import java.util.ArrayList;
public class Encrypt {
public static ArrayList<String> data = new ArrayList<String>();
public static BigInteger [] keys = new BigInteger[3];
public static BigInteger n;
public static double e;
public static BigInteger d;
public static String line;
public static String result;
public static String [] temp;
public static BigInteger tempVar;
public static BigInteger tempResult;
public static int tempVar2;
public static void encryption(ArrayList<String> data) throws IOException{
for (int i = 0; i<data.size(); i++){
if(data.get(i)!= null){
temp = new String[data.get(i).split(" ").length];
temp = data.get(i).split(" ");
for(int j = 0; j<temp.length;j++){
for (int k = 0; k< temp[j].length(); k++){
tempVar2 = (int)temp[j].charAt(k);
tempVar=BigInteger.valueOf((long)Math.pow(tempVar2,e));
tempResult = (tempVar.remainder(n));
result =""+ tempResult;
LogEncrypt(result);
}
}
}
}
}
public static void read() throws IOException{
try {
BufferedReader br = new BufferedReader(new FileReader("plainText.txt"));
System.out.println(br.ready());
while ((line = br.readLine()) != null) {
data.add(br.readLine());
}
System.out.println("done with text");
} catch (FileNotFoundException e) {
System.out.println("please add the text file");
e.printStackTrace();
}
try {
BufferedReader ba = new BufferedReader(new FileReader("Key.txt"));
System.out.println(ba.ready());
int i =0;
while ((line = ba.readLine()) != null) {
keys[i] = new BigInteger(ba.readLine());
i++;
}
n = keys[0];
e = keys[1].doubleValue();
d = keys[2];
System.out.println("done with key");
} catch (FileNotFoundException e) {
System.out.println("please add the key file");
e.printStackTrace();
}
}
public static void LogEncrypt(String result) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("output.txt"));
try {
out.write(result);
out.newLine();
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
}
}
public static void main(String[]args) throws IOException{
read();
encryption(data);
}
}
Put the file outside of the src, or at least add "src/" to the file location

Categories

Resources