Now I am trying to read txt files and make an array in arraylist with that data.
I want to read two txt files and compare them, but I can't understand why the inside while loop is not working.
(I used 'count' variable to test inside while loop, but when I printed count variable, it printed only 0.)
(Also I know that try~ catch~ is not good solution for
NullPointerException error.. but I couldn't find other solution instead of try~ catch~)
import java.io.*;
import java.util.*;
public class Warehouse {
static private String[] eachStockElem = new String[5];
static private String[] eachInputElem = new String[5];
public static void main(String[] args) throws Exception {
Scanner str = new Scanner(new File("a.txt"));
Scanner ip = new Scanner(new File("b.txt"));
PrintStream st_w = new PrintStream("a.txt");
PrintStream tx = new PrintStream("c.txt");
ArrayList<String[]> stockArrayList = new ArrayList<>();
ArrayList<String[]> inputArrayList = new ArrayList<>();
ArrayList<String[]> txArrayList = new ArrayList<>();
String eachTxElem[] = new String[6];
int tx_id=0;
int temp_quantity=0;
int count=0;
try {
while (ip.hasNextLine()) {
eachInputElem = ip.nextLine().split(",");
inputArrayList.add(eachInputElem);
while (str.hasNextLine()) { //this while not working!
eachStockElem = str.nextLine().split(",");
stockArrayList.add(eachStockElem);
count++;
//do comparing operation
break;
}
}
}
catch(NullPointerException e){
System.out.print("");
}
System.out.println(count);
str.close();
ip.close();
tx.close();
}
}
By guessing what "this loop does not work" words mean, i am taking the risk to post of what i think is the problem in your case.
PrintStream in documents:
The name of the file to use as the destination of this print stream.
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.
The problem (and the answer, "why it is not working"):
Scanner str = new Scanner(new File("a.txt"));
PrintStream st_w = new PrintStream("a.txt"); //Cleans the text file,
// so scanner has no lines to read.
At this line,
PrintStream st_w = new PrintStream("a.txt");
the program is writing the output in the same input file. Change the name of this output file and execute your test case.
Related
I'm supposed to be coding an app that can read names from a hardcoded text file, save them as a string array, then write those names in a different text file but sorted. I believe I have the first two parts down but I'm confused on how to sort the names then write them into a new file.
These is the actual problem I'm working on:
"Take an input file with 10 names in it (hard coded). Write a program to read the file, save the names in a String array and write into a different file names in sorted order. Use Methods appropriately."
BTW I'm a rookie coder, this is what I have so far.
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
readFile();
saveStringArray();
}
public static void readFile() {
File file = new File("/Users/nicoladaaboul/Desktop/Programming/C++, "
+ "HTML5, Java, PHP/Java/Question2/names.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String i = sc.next();
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void saveStringArray() throws FileNotFoundException {
String token1 = "";
Scanner inFile1 = new Scanner(new File("names.txt")).useDelimiter(",\\s*");
List<String> temps = new ArrayList<String>();
while (inFile1.hasNext()) {
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
Arrays.sort(tempsArray);
for (String s : tempsArray) {
System.out.println(s);
}
}
public static void sortingNames() {
}
public static void writingFile() throws FileNotFoundException {
PrintWriter writer = new PrintWriter("sortedNames.txt");
writer.close();
}
Its important that you break your problem down into instructions.
1. You need to read the file you can use bufferedReader(code below).
2. Create an array(or arraylist) to store your string values.
3. Then as you read each line, store these values in the array.
4. When finished reading the file you then would pass this array to a function that would sort it(Why does my sorting loop seem to append an element where it shouldn't?).
5. Once sorted you simply write this array, to a file.
BufferedReader br = new BufferReader(new FileReader("name.txt"));
int count = 0;
String line;
String[] names = new String[100];
while((line = br.nextLine()) != null){
names[count] = line;
count++;
}
Hey guys I'm trying to read in a file which I have done many times before, but It keeps outputting "null" for however many lines of code exist in the .
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
String[] item = new String[25];
Scanner fileInput;
File inFile = new File("dictionary.txt");
try {
fileInput = new Scanner(inFile);
int newItem = 0;
while (fileInput.hasNext())
{
item[newItem++] = fileInput.nextLine();
System.out.println(item[newItem]);
}
}
catch(FileNotFoundException e){System.out.println(e); }
txt file. please help.
You increment newItem and then you print item[newItem]. It always return null because you have not written anything yet in item for the new index.
Try:
while (fileInput.hasNext()) {
item[newItem] = fileInput.nextLine();
System.out.println(item[newItem]);
newItem++;
}
It's because of newItem++, which returns the value and then increments it.
So, you start by setting item[x] = ...; - but then print out item[x+1];
So I have a background in c++ and I am trying to learn java. Everything is pretty similar. I am having a problem thought with file i/o. So I am messing around and doing really simple programs to get the basic ideas. Here is my code to read data from a file. So I am reading Core Java Volume 1 by Cay Hortsman and it tells me to write this to read from a file,
Scanner in = new Scanner(Paths.get("myFile.txt");
But when I write it in my code, it gives me a red line under paths. So I am not sure how to read from a file. It does not go into much detail about the subject. So my program below I am trying to just read numbers in from a file and store them in an array.
package practice.with.arrays.and.io;
import java.io.IOException;
import java.nio.file.Path;
import java.util.*;
public class PracticeWithArraysAndIO
{
static final int TEN = 10;
public static void main(String[] args) throws IOException
{
//Declaring a scanner object to read in data
Scanner in = new Scanner(Paths.get("myFile.txt"));
//Declaring an array to store the data from the file
int[] arrayOfInts = new int[TEN];
//Local variable to store data in from the file
int data = 0;
try
{
for(int i = 0; i < TEN; i++)
{
data = in.nextInt();
arrayOfInts[i] = data;
}
}
finally
{
in.close();
}
}
It is not clear why you are doing Paths.get(filename)).
You can wrap a Scanner around a file like this. As the comments below mention, you should choose an appropriate charset for your file.
Scanner in = new Scanner(new File("myFile.txt"), StandardCharsets.UTF_8);
To use the constant above, you need the following import, and Java 7.
import java.nio.charset.StandardCharsets
With my experience in Java, I've used the BufferedReader class for reading a text file instead of the Scanner. I usually reserve the Scanner class for user input in a terminal. Perhaps you could try this method out.
Create a BufferedReader with FileReader like so:
BufferedReader buffReader = new BufferedReader(new FileReader("myFile.txt"));
After setting this up, you can read lines with:
stringName = buffReader.readLine();
This example will set the String, stringName, to the first line in your document. To continue reading more lines, you'll need to create a loop.
You need to import java.nio.file.Paths.
I've used the BufferedReader class.
I hope it is helpful for you
public class PracticeWithArraysAndIO {
static final int TEN = 10;
public static void main(String[] args) throws IOException
{
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader("/home/myFile.txt"));//input your file path
int value=0;
int[] arrayOfInts = new int[TEN];
int i=0;
while((value = br.read()) != -1)
{
if(i == 10) //if out of index, break
break;
char c = (char)value; //convert value to char
int number = Character.getNumericValue(c); //convert char to int
arrayOfInts[i] = number; //insert number into array
i++;
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(br != null)
br.close(); //buffer close
}
}
}
I want to separate the elements of a text file into different arrays based of whether or not the line contains a question mark. Here is as far as I got.
Scanner inScan = new Scanner(System.in);
String file_name;
System.out.print("What is the full file path name?\n>>");
file_name = inScan.next();
Scanner fScan = new Scanner(new File(file_name));
ArrayList<String> Questions = new ArrayList();
ArrayList<String> Other = new ArrayList();
while (fScan.hasNextLine())
{
if(fScan.nextLine.indexOf("?"))
{
Questions.add(fScan.nextLine());
}
Other.add(fScan.nextLine());
}
Quite a few issues there
nextLine() actually returns the next line and moves on the scanner, so you'll need to read once instead
indexOf returns an int, not a boolean, I'm guessing you're more use to C++? You can use any of the following instead:
indexOf("?") >=0
contains("?")
matches("\?") etc.
please follow the java ways and use camelCase for vars...
Code
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("foo.txt"));
List<String> questions = new ArrayList<String>();
List<String> other = new ArrayList<String>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("?")) {
questions.add(line);
} else {
other.add(line);
}
}
System.out.println(questions);
System.out.println(other);
}
foo.txt
line without question mark
line with question mark?
another line
I was trying to take the input of the filename from the user and then proceed to doing all the calculations. but it keeps returning me an error. the file exists in the same directory.
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) throws FileNotFoundException {
//File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(System.in);
scanner.nextLine(); // removes the first line in the input file
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());
String colLine = scanner.nextLine();
String[] arr2 = colLine.split("=");
int cols = Integer.parseInt(arr2[1].trim());
double [][]matrix = new double [rows][cols];
for (int i=0; i<rows;i++){
for (int j=0; j<cols;j++) {
matrix[i][j]= scanner.nextDouble();
}
}
System.out.println(rows);
System.out.println(cols);
for (int i=0; i<rows; i++)
{ for (int j=0;j<cols;j++) {
System.out.println(matrix[i][j]);
}
}
}
}
There is one issue with the code. The scanner will just give you the name of the file as string from command line. So, you need to first get the command line argument and then create one more scanner using the constructor which takes file object. e.g.
Scanner scanner = new Scanner(System.in);
Scanner fileScanner = new Scanner(new File(scanner.nextLine()));
String rowLine = fileScanner.nextLine();
System.out.println(rowLine);
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim())
You realize that you are only using a Scanner of type System.in, right? This means that you aren't even looking at a file, you are looking at user input only. This is regardless of whether you have the first line commented out or not. To use a file, you could use a FileInputStream or a couple other File handling classes.
FileInputStream fs = new FileInputStream(new File("matrix1.txt"));
//do stuff with the stream
Heres the java docs for FileInputStream: http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileInputStream.html
Edit: After seeing your comment on what the actual error was, I realize there are more problems with the code than just the way you are handling input. Your error is almost certainly happening at one of the first 2 array accessors, the arr1.trim() calls. That means the user input has nothing on the right side of the "=" sign, or there is no "=" sign in the user input.