Reading standard(console) input from file and printing output to other file - java

What I'm trying to do is to make my program read input test-cases from a file instead of standard console input and write back the output to another file.
Here comes the problem into play, if I'm trying to give input using file it is showing java.lang.NullPointerException, but on other hand giving correct output if I'm trying to give custom standard input(using cmd) and printing output to a file.
Here is my sample program:
public class Roman
{
static private final String INPUT = "Q4.in";
static private final String OUTPUT = "Q4.out";
// open I/O files
public static void main(String[] args)
{
FileInputStream instream = null;
PrintStream outstream = null;
try {
instream = new FileInputStream(INPUT);
outstream = new PrintStream(new FileOutputStream(OUTPUT));
System.setIn(instream);
System.setOut(outstream);
} catch (Exception e) {
System.err.println("Error Occurred.");
}
int i;
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
Num2Rom[] tc=new Num2Rom[T];
for(i=0;i<T;i++)
{ tc[i]=new Num2Rom(); }
System.out.println(T+"\n");
for(i=0;i<T;i++)
{ tc[i].display(i+1); }
}
}
and
ArrayList<String> wordList;
Num2Rom()
{
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String numeral = sc.nextLine();
System.out.println("print"+numeral);
numeral = numeral.toUpperCase();
String[] words = numeral.split(" ");
wordList = new ArrayList<>(Arrays.asList(words)); }
}
The input is formatted as:
2
Eight
Twenty

You can use java command line arguements to give input to the program.
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
do convert the arguments to the desired type,as arguments are received in the string format.
such as if you want an integere you can convert using
int value=Integer.parseInt($args[0]);

Related

Scanner for input file and storing data objects from input file in array

Basically, I had to create a scanner for a given file and read through the file (the name is input through the terminal by the user) once counting the number of lines in the file. Then after, I had to create an array of objects from the file, of the correct size (where the num of lines comes in). Then I had to create another scanner for the file and read through it again, storing it in the array I created. And lastly, had to return the array in the method.
My problem is I cannot seem to get the second scanner to actually store the file objects in the array.
I've tried using .nextLine inside a for loop that also calls the array, but it doesn't seem to be working.
public static Data[] getData(String filename) {
Scanner input = new Scanner(new File(filename));
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
System.out.println(count);
Data[] data = new Data[count];
Scanner input1 = new Scanner(new File(filename));
while (input1.hasNextLine()) {
for (int i = 0; i < count; i++) {
System.out.println(data[i].nextLine);
}
}
return data;
}
I expect the output to successfully read the input file so that it can be accessed by other methods that I have created (not shown).
You should definitely use an IDE if you don't have one, try intellij... There you have autocompletion and syntax checking and much more.
It is not clear what you want to do in your for loop, because there are several mistakes, for example the readline() function works only with the scanner objekt, so you can do input.nextline() or input1.nextline()`...
so I just show you, how you can get the Data from a file with Scanner:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Readfile {
public static void getData(String filename) throws FileNotFoundException {
ArrayList<String> test = new ArrayList<>(); //arraylist to store the data
Scanner inputSc = new Scanner(new File(filename)); //scanner of the file
while (inputSc.hasNextLine()) {
String str = inputSc.nextLine();
System.out.println(str); //print the line which was read from the file
test.add(str); //adds the line to the arraylist
//for you it would be something like data[i] = str; and i is a counter
}
inputSc.close();
}
public static void main(String[] args) {
try {
getData("/home/user/documents/bla.txt"); //path to file
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You don't need to read thru the file twice - just use an ArrayList to hold the data that's coming in from the file, like this, and then return Data[] at the end:
public static Data[] getData(String filename) {
List<Data> result = new ArrayList<>();
try (Scanner input = new Scanner(new File(filename))){
while (input.hasNextLine()) {
Data data = new Data(input.nextLine());
result.add(data);
}
}
return result.toArray(new Data[0]);
}
Not clear what Data.class do you mean, if you switch it to String, the problem obviously would be in this line
System.out.println(data[i].nextLine);
if you want to assign and print simultaneously write this
for (int i = 0; i < count; i++) {
data[i] = input1.next();
System.out.println(data[i]);
}
and dont forget to close your Scanners, better use try-with-resources.
If your Data is your custom class you'd better learn about Serialization-Deserialization
Or use some ObjectMapper-s(Jackson, for example) to store your class instances and restore them.
Your way of opening the file just to count the lines and then again looping through its lines to store them in the array is not that efficient, but it could be just a school assignment.
Try this:
public static Data[] getData(String filename) {
Scanner input = null;
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
input.close();
System.out.println(count);
Data[] data = new Data[count];
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
for (int i = 0; i < count; i++) {
Data d = new Data(input.nextLine(), 0, 0);
data[i] = d;
System.out.println(data[i].name);
}
input.close();
return data;
}
After the 1st loop you must close the Scanner and reopen it so to start all over from the first line of the file.

Declare size of an array at Runtime

I'm coding a program that copy the contents of all the files to the last input file taken( all the files are given by the user at Command prompt). So, how can I declare an array that takes the size from the user?
Do it like that:
import java.util.Scanner; <-------- import the class
public class InputFromUser {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number for the array size:");
int size = scan.nextInt();
int[] arr = new int[size];
}
}
Either use java.io like this:
BufferedReader columnInput = new BufferedReader(new InputStreamReader (System.in));
int size = Integer.parseInt(columnInput.readLine());
If the list of files supplied when running the application as arguments : you can use the args.length property which returns the number of the supplied arguments:
public static void main(String[] args) {
System.out.println(args.length);
}
You can also do in this way :
public static void main(String args[]) {
BufferedReader input = new BufferedReader (new InputStreamReader(System.in));
try {
System.out.println("Enter a array size:");
int arraysize = Integer.parseInt(input.readLine());
int[] arr = new int[arraysize];
} catch (Exception e) {
e.printStackTrace();
}
}

Reversing arraylist not working properly

My task is to read from an input file test.txt, this text has some sentences.
I need to write a class with a constructor and three methods.
One of which has to reverse the order of the words in a sentence.
import java.util.*;
import java.io.*;
public class Reverser {
Scanner sc3 = null ;
//constructor takes input file and initialize scanner sc pointing at input
public Reverser(File file)throws FileNotFoundException, IOException{
sc3 = new Scanner (file);
}
//this method reverses the order of the words in each line of the input
//and prints it to output file specified in argument.
public void reverseEachLine(File outpr)throws FileNotFoundException, IOException{
// ArrayList<String> wordsarraylist = new ArrayList<String>();
while(sc3.hasNextLine()){
String sentence = sc3.nextLine();
// int length = sentence.length();
String[] words = sentence.split(" ");
// wordsarraylist.clear();
List<String> wordsarraylist = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.close();
}
}
}
I have removed two other methods but they don't interfere with this one.
And this is my main:
import java.io.*;
public class DemoReverser {
public static void main (String [] args)
throws IOException, FileNotFoundException {
Reverser r = new Reverser(new File("test.txt"));
r.reverseEachLine(new File("out2.txt"));
}
}
The problem is that at the end of the execution my output file contains the same thing. It is not reversing the order. How come? doesn't Collections.reverse() reverse the order? And so when I print it I should have the words in reverse?
I am also required to use arraylist.
This my input file:
This is just a small file. That
has some lines of text.
If we are successful, these
lines will be
reversed.
Let's hope for the best!
I am supposed to get this in my output:
That file. small a just is This
text. of lines some has
these successful, are we If
be will lines
reversed.
best! the for hope Let's
But i am getting this:
This is just a small file. That
has some lines of text.
If we are successful, these
lines will be
reversed.
Let's hope for the best!
Try this code for the method reverseEachLine, it works fine. Don't construct Scanner at the constructor.
public class MyReverser {
private File inputFile;
public MyReverser(File file) {
this.inputFile = file;
}
public void reverseEachLine(File outpr) throws FileNotFoundException, IOException {
Scanner sc = new Scanner(inputFile);
ArrayList<List<String>> wordsarraylist = new ArrayList<List<String>>();
while (sc.hasNextLine()) {
String sentence = sc.nextLine();
List words = Arrays.asList(sentence.split(" "));
Collections.reverse(words);
wordsarraylist.add(words);
}
FileWriter writer = new FileWriter(outpr, false);
for (List<String> list : wordsarraylist) {
for (String string : list) {
writer.append(string + " ");
}
writer.append(System.lineSeparator());
}
writer.flush();
writer.close();
}
}
I have answered here with full code java cannot create file by 3 methods

how to add string read from file to an ArrayList?

I have a super beginner's question. I have a computer science test today and one of the practice problems is this:
Write a program that carries out the following tasks:
Open a file with the name hello.txt.
Store the message “Hello, World!” in the file.
Close the file.
Open the same file again.
Read the message into a string variable and print it.
This is the code I have for it so far:
import java.util.*;
import java.io.*;
public class ReadFile
{
public static void main(String[] args) throws FileNotFoundException
{
PrintWriter out = new PrintWriter("hello.txt");
out.println("Hello, World");
File readFile = new File("hello.txt");
Scanner in = new Scanner(readFile);
ArrayList<String> x = new ArrayList<String>();
int y = 0;
while (in.hasNext())
{
x.add(in.next());
y++;
}
if (x.size() == 0)
{
System.out.println("Empty.");
}
else
{
System.out.println(x.get(y));
}
in.close();
out.close();
}
}
What's wrong with this code?
1) You need to close the stream
2) You need to refer to the x Arraylist with (y-1) otherwise you will get
a java.lang.IndexOutOfBoundsException . The indexes starts from 0 and not from 1.
http://www.tutorialspoint.com/java/util/arraylist_get.htm
public static void main(String[] args) throws FileNotFoundException
{
PrintWriter out = new PrintWriter("hello.txt");
out.println("Hello, World");
out.close();
File readFile = new File("hello.txt");
Scanner in = new Scanner(readFile);
ArrayList<String> x = new ArrayList<String>();
int y = 0;
while (in.hasNext())
{
x.add(in.next());
y++;
}
in.close();
if (x.size() == 0)
{
System.out.println("Empty.");
}
else
{
System.out.println(x.get(y-1));
}
}
}
I guess what's wrong with the code ist that you cant read anything from the file.
this is because PrintWriter is buffered
fileName - The name of the file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
You need to close the file you have just writen to before openning it for reading so that the changes are fluched to the physical storage. Thus moving out.close(); right after out.println("Hello, World");
class FileWritingDemo {
public static void main(String [] args) {
char[] in = new char[13]; // to store input
int size = 0;
try {
File file = new File("MyFile.txt"); // just an object
FileWriter fw = new FileWriter(file); // create an actual file & a FileWriter obj
fw.write("Hello, World!"); // write characters to the file
fw.flush(); // flush before closing
fw.close(); // close file when done
FileReader fr = new FileReader(file); // create a FileReader object
size = fr.read(in); // read the whole file!
for(char c : in) // print the array
System.out.print(c);
fr.close(); // again, always close
} catch(IOException e) { }
}
}

Error: java.util.NoSuchElementException - Scanner not behaving as desired

Scanner returning NoSuch Element Exception error. Could you explain why is this happening.
The Scanner now passes and runs fine but it didn't take the nextLine input from the second Scanner call. This may be a little tweak but could someone point out what the mistake is.
public class JavaHW1_1 {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) throws IOException {
String pattern ;
String fileName = null;
// Method to manage user inputs
fileName = userInputFileName(userInput);
pattern = userInputPattern(userInput);
// To find the pattern in the file
// findPattern();
}
private static String userInputPattern(Scanner userInput) {
String pattern = "JollyGood";
System.out.println(". Please enter a pattern to find in the file");
while(userInput.hasNextLine()){
pattern = userInput.nextLine();
System.out.println("The pattern to be searched: "+ pattern);
}
userInput.close();
return pattern;
}
private static String userInputFileName(Scanner userInput) throws IOException {
String path = "./src";
String files, fileName;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
System.out.println("Please input the desired file name:\n");
System.out.println("Some suggestions:\n");
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile() && listOfFiles[i].getName().toLowerCase().endsWith(".txt"))
{
files = listOfFiles[i].getName();
System.out.println(files);
}
}
int userAttempt = 0;
do{
fileName = userInput.nextLine();
if(fileName.toLowerCase().endsWith(".txt")){
System.out.println("The file name entered is in correct format");
File file = new File("./src",fileName);
try {
file.createNewFile();
System.out.println("File is created. Please enter text to be written in the file. End the content with \"eof\"");
InputOutput(file.getName());
} catch (IOException e) {
e.printStackTrace();
}
userAttempt = 10;
}
else
{System.out.println("Please enter correct format file with .txt extension");
userAttempt++;}
}while (userAttempt <10);
return fileName;
}
private static void InputOutput(String fName) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("./src/" + fName));
String inputLine = null;
do {
inputLine=in.readLine();
out.write(inputLine);
out.newLine();
} while (!inputLine.equalsIgnoreCase("aaa"));
System.out.print("Write Successful");
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
in.close();
}
}
private static void findPattern() {
// TODO Auto-generated method stub
}
}
Based in this SO, you might be closing the Scanner and creating a new one to read from the System.in and it makes sense by looking at your code.
So my suggestion for you code is to receive the Scanner by parameter, something like this:
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
String pattern = userInputPattern(scan);
String test = readSomethingElse(scan);
}
private static String readSomethingElse(Scanner scan) {
System.out.println(". Read something else");
return scan.nextLine();
}
private static String userInputPattern(Scanner scan) {
String pattern = "JollyGood";
System.out.println(". Please enter a pattern to find in the file");
pattern = scan.nextLine();
System.out.println("The pattern to be searched: "+ pattern);
return pattern;
}
It could happen if you pass EOF straight into the standard input. For example (in windows):
java com.myprog.MainClass
^Z
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
....
The ^Z above represents a Ctrl-Z on windows command prompt which is an EOF signal
You need to consider your requirement and process / display error if user is provided a EOF without any prior data

Categories

Resources