Reading a file of txt to be fed into an array - java

Here a user enters a list of 1's and 0's.... so an input would 10001010. However I want it to read from a text file... my text file input.txt also containes 10001010... need the coverDataArray array to be fed the same string from the console as from a file.
I tried Datainput stream however, it throws me the exception
'
Scanner in = new Scanner (System.in);
String data1="";
...
.....
try{
System.out.println("Enter the binary bits");
data1 = in.next();
for ( int i = 0; i < data1.length(); i++)
{
covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
}'

You can pass a File Object instead of System.in to Scanner constructor. Try it as shown below:
String fileName = "input.txt";
File file = new File(fileName);
Scanner scanner = new Scanner(file);
String s = "";
while(scanner.hasNextLine()){
s = scanner.nextLine();
// your code. You can also use scanner.next() to read word by word instead of nextLine()
}

Byte.parseByte(data1.substring( i, i+1));
Your exception is caused by the fact that you're going up to length - 1, then length - 1 + 1, which is length, which is goign to cause your ArrayOutOfBoundsException. This can be seen on this line:
covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
At one point, i is equal to length-1, or the last index in your String. You then attempt to access the next element, which doesn't exist.
And as for your file, you can pass a File object into the Scanner.
Example
Either..
File file = new File("yourfile.txt");
Scanner s = new Scanner(file);

You are trying to use Byte.parseByte as a methode of parsing binairy input, this doesn't really work as parseByte will try to take a numerical input and parse it into a number between -128 and 127. You should use a different method.

Related

This code is supposed to get N values from the user. Then input then into a .txt file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This code is supposed to get N values from the user. Then input the values into a .txt file. I'm having trouble getting the values to show in the .txt file. Not sure why.
// This program writes data into a file.
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("namef.txt");
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
PrintWriter outputfile = new PrintWriter("/Users/******/Desktop/namef.txt");
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for ( int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
input.nextInt();
outputfile.print(N);
}
System.out.println("Data entered into the file.");
inputFile.close(); // Close the file.
}
} // End of class
In your program you seemed to have thrown everything and hoping that it works. To find out what class you should use you should search it in Javadoc of you Java version.
Javadoc of Java 12
PrintWriter:
Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
FileWriter:
Writes text to character files using a default buffer size. Encoding from characters to bytes uses either a specified charset or the platform's default charset.
Scanner (File source):
Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.
Now you can see what each class is for. Both PrintWriter and FileWriter are used to write file however PrintWriter offer more formatting options and Scanner(File source) is for reading files not writing files.
Since there is already an answer with PrintWriter. I am writing this using FileWriter.
public static void main(String[] args) throws Exception {
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
// You can provide file object or just file name either would work.
// If you are going for file name there is no need to create file object
FileWriter outputfile = new FileWriter("namef.txt");
System.out.print("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++) {
System.out.print("Enter the number into the file: ");
// Writing the value that nextInt() returned.
// Doc: Scans the next token of the input as an int.
outputfile.write(Integer.toString(input.nextInt()) + "\n");
}
System.out.println("Data entered into the file.");
input.close();
outputfile.close(); // Close the file.
}
Output:
Enter the number of data (N) you want to store in the file: 2
Enter 2 numbers below:
Enter the number into the file: 2
Enter the number into the file: 1
Data entered into the file.
File:
2
1
Here's a working variant of what you want to achieve:
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("path/to/your/file/namef.txt");
PrintWriter outputfile = new PrintWriter(fname);
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
int tmp = input.nextInt();
outputfile.print(tmp);
}
System.out.println("Data entered into the file.");
outputfile.close(); // Close the file.
}
}
Several comments on above:
1) Got rid of redundant rows:
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
You actually didn't use them at all.
2) In PrintWriter we pass File object, not String.
3) In for loop there was a logic mistake - on every iteration you should have written N instead of actual number which user entered on console.
4) Another mistake was in closing wrong file in the last line.
EDIT: adding according to comment.
in point 2) there's an alternative way - you can skip creating File object and pass as a String a path to even non-existing file directly in PrintWriter, like this:
PrintWriter outputfile = new PrintWriter("path/to/your/file/namef.txt");

Read data from file and convert to key value pair

I have the below integers in File :
758 29
206 58
122 89
I have to read these integers in an integer array and then need to store the values in key value pair. Then print the output as :
Position 29 has been initialized to value 758.
Position 89 has been initialized to value 122.
I have tried as of now :
private static Scanner readFile() {
/*
* Your program will prompt for the name of an input file and the read
* and process the data contained in this file. You will use three
* integer arrays, data[], forward[] and backward[] each containing 100
* elements
*/
int data[] = new int[100];
int forward[] = new int[100];
int backward[] = new int[100];
System.out.print("Please enter File Name : ");
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
String filename = scanner.nextLine();
File inputFile = new File(filename);
Scanner linReader = null;
try {
linReader = new Scanner(new File(filename));
while (linReader.hasNext()) {
String intStringSplit = linReader.nextLine();
String[] line = intStringSplit.split("\t",-1);
data = new int[line.length];
for (int i = 0; i < data.length; i++) {
data[i] = Integer.parseInt(line[i]);
}
System.out.println(data);
}
linReader.close();
} catch (Exception e) {
System.out.println("File Not Found");
}
return linReader;
}
I am not able to figure out how to get the key and value from the read data.
When posting information related to your question it is very important that you provide the data (in file for example) exactly as it is intended in reality so that we can make a more positive determination as to why you are experiencing difficulty with your code.
What you show as an in file data example indicates that each file line (which contains actual data) consists of two specific integer values. The first value being the initialization value and the second being the position value.
There also appears to be a blank line after ever line which contains actual data. This really doesn't matter since the code provided below has a code line to take care of such a thing but it could be the reason as to why you may be having difficulty.
To me, it looks like the delimiter used to separate the two integer values in each file line is indeed a whitespace as #csm_dev has already mentioned within his/her comment but you claim you tried this in your String.split() method and determined it is not a whitespace. If this is truly the case then it will be up to you to determine exactly what that delimiter might be. We couldn't possibly tell you since we don't have access to the real file.
You declare a File object within your provided code but yet nowhere do you utilize it. You may as well delete it since all it's doing is sucking up oxygen as far as I'm concerned.
When using try/catch it's always good practice to catch the proper exceptions which in this case is: IOException. It doesn't hurt to also display the stack trace as well upon an exception since it can solve a lot of your coding problems should an exception occur.
This code should work:
private static Scanner readFile() {
/*
* Your program will prompt for the name of an input file and the read
* and process the data contained in this file. You will use three
* integer arrays, data[], forward[] and backward[] each containing 100
* elements
*/
int data[] = new int[100];
int forward[] = new int[100];
int backward[] = new int[100];
System.out.print("Please enter File Name : ");
Scanner scanner = new Scanner(System.in);
String filename = scanner.nextLine();
File inputFile = new File(filename); // why do you have this. It's doing nothing.
Scanner linReader = null;
try {
linReader = new Scanner(new File(filename));
while (linReader.hasNext()) {
String intStringSplit = linReader.nextLine();
// If the file line is blank then just
// continue to the next file line.
if (intStringSplit.trim().equals("")) { continue; }
// Assuming at least one whitespace is used as
// the data delimiter but what the heck, we'll
// use a regular expression within the split()
// method to handle any number of spaces between
// the integer values.
String[] line = intStringSplit.split("\\s+");
data = new int[line.length];
for (int i = 0; i < line.length; i++) {
data[i] = Integer.parseInt(line[i]);
}
System.out.println("Position " + data[1] +
" has been initialized to value " +
data[0] + ".");
// do whatever else you need to do with the
// data array before reading in the next file
// line......................................
}
linReader.close();
}
catch (IOException ex) {
System.out.println("File Not Found");
ex.printStackTrace();
}
return linReader;
}

Printing out the number of lines a file contains

At the moment my code does nothing when i input a valid .txt file. I would like to print the number of lines the file contains. Could anyone tell me why nothing is currently happening?
public class Task3
{
public static void main(String[] args) throws FileNotFoundException
{
// instance variables
int characterCount = 0;
int wordCount = 0;
int lineCount = 0;
// create a Scanner object to read in file name from console input
Scanner in = new Scanner(System.in);
System.out.print("Please enter the file name: ");
String filename = in.next();
File inputFile = new File(filename);
// create a Scanner object to read the actual text file
Scanner inFile = new Scanner(inputFile);
int lines = 0;
while (inFile.hasNextLine())
{ // enter while loop if there is a complete line available
in.nextLine();
lines++;
// increase line counter variable
}
System.out.println(lines);
You're not reading lines from the file, you're reading them from standard input.
In this loop:
while (inFile.hasNextLine())
{ // enter while loop if there is a complete line available
in.nextLine();
lines++;
// increase line counter variable
}
You are using the Scanner for System.in, not the scanner you created for the file. So the call to nextLine will wait for your input instead of going to the next line in the file. That's why it seems that nothing is happening.
Replace in.nextLine with inFile.nextLine and it will work.
Change:
in.nextLine();
To:
inFile.nextLine();
Add a System.out.println(inputFile.exists()) to see that you are not creating a new file.

How to read data from a text file into arrays in Java

I am having trouble with a programming assignment. I need to read data from a txt file and store it in parallel arrays. The txt file contents are formatted like this:
Line1: Stringwith466numbers
Line2: String with a few words
Line3(int): 4
Line4: Stringwith4643numbers
Line5: String with another few words
Line6(int): 9
Note: The "Line1: ", "Line2: ", etc is just for display purposes and isn't actually in the txt file.
As you can see it goes in a pattern of threes. Each entry to the txt file is three lines, two strings and one int.
I would like to read the first line into an array, the second into another, and the third into an int array. Then the fourth line would be added to the first array, the 5th line to the second array and the 6th line into the third array.
I have tried to write the code for this but can't get it working:
//Create Parallel Arrays
String[] moduleCodes = new String[3];
String[] moduleNames = new String[3];
int[] numberOfStudents = new int[3];
String fileName = "myfile.txt";
readFileContent(fileName, moduleCodes, moduleNames, numberOfStudents);
private static void readFileContent(String fileName, String[] moduleCodes, String[] moduleNames, int[] numberOfStudents) throws FileNotFoundException {
// Create File Object
File file = new File(fileName);
if (file.exists())
{
Scanner scan = new Scanner(file);
int counter = 0;
while(scan.hasNext())
{
String code = scan.next();
String moduleName = scan.next();
int totalPurchase = scan.nextInt();
moduleCodes[counter] = code;
moduleNames[counter] = moduleName;
numberOfStudents[counter] = totalPurchase;
counter++;
}
}
}
The above code doesn't work properly. When I try to print out an element of the array. it returns null for the string arrays and 0 for the int arrays suggesting that the code to read the data in isn't working.
Any suggestions or guidance much appreciated as it's getting frustrating at this point.
The fact that only null's get printed suggests that the file doesn't exist or is empty (if you print it correctly).
It's a good idea to put in some checking to make sure everything is fine:
if (!file.exists())
System.out.println("The file " + fileName + " doesn't exist!");
Or you can actually just skip the above and also take out the if (file.exists()) line in your code and let the FileNotFoundException get thrown.
Another problem is that next splits things by white-space (by default), the problem is that there is white-space on that second line.
nextLine should work:
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = Integer.parseInt(scan.nextLine());
Or, changing the delimiter should also work: (with your code as is)
scan.useDelimiter("\\r?\\n");
You are reading line so try this:
while(scan.hasNextLine()){
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = Integer.pasreInt(scan.nextLine().trim());
moduleCodes[counter] = code;
moduleNames[counter] = moduleName;
numberOfStudents[counter] = totalPurchase;
counter++;
}
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = scan.nextInt();
scan.nextLine()
This will move scanner to proper position after reading int.

How to determine the end of a line with a Scanner?

I have a scanner in my program that reads in parts of the file and formats them for HTML. When I am reading my file, I need to know how to make the scanner know that it is at the end of a line and start writing to the next line.
Here is the relevant part of my code, let me know if I left anything out :
//scanner object to read the input file
Scanner sc = new Scanner(file);
//filewriter object for writing to the output file
FileWriter fWrite = new FileWriter(outFile);
//Reads in the input file 1 word at a time and decides how to
////add it to the output file
while (sc.hasNext() == true)
{
String tempString = sc.next();
if (colorMap.containsKey(tempString) == true)
{
String word = tempString;
String color = colorMap.get(word);
String codeOut = colorize(word, color);
fWrite.write(codeOut + " ");
}
else
{
fWrite.write(tempString + " ");
}
}
//closes the files
reader.close();
fWrite.close();
sc.close();
I found out about sc.nextLine(), but I still don't know how to determine when I am at the end of a line.
If you want to use only Scanner, you need to create a temp string instantiate it to nextLine() of the grid of data (so it returns only the line it skipped) and a new Scanner object scanning the temp string. This way you're only using that line and hasNext() won't return a false positive (It isn't really a false positive because that's what it was meant to do, but in your situation it would technically be). You just keep nextLine()ing the first scanner and changing the temp string and the second scanner to scan each new line etc.
Lines are usually delimitted by \n or \r so if you need to check for it you can try doing it that way, though I'm not sure why you'd want to since you are already using nextLine() to read a whole line.
There is Scanner.hasNextLine() if you are worried about hasNext() not working for your specific case (not sure why it wouldn't though).
you can use the method hasNextLine to iterate the file line by line instead of word by word, then split the line by whitespaces and make your operations on the word
here is the same code using hasNextLine and split
//scanner object to read the input file
Scanner sc = new Scanner(file);
//filewriter object for writing to the output file
FileWriter fWrite = new FileWriter(outFile);
//get the line separator for the current platform
String newLine = System.getProperty("line.separator");
//Reads in the input file 1 word at a time and decides how to
////add it to the output file
while (sc.hasNextLine())
{
// split the line by whitespaces [ \t\n\x0B\f\r]
String[] words = sc.nextLine().split("\\s");
for(String word : words)
{
if (colorMap.containsKey(word))
{
String color = colorMap.get(word);
String codeOut = colorize(word, color);
fWrite.write(codeOut + " ");
}
else
{
fWrite.write(word + " ");
}
}
fWrite.write(newLine);
}
//closes the files
reader.close();
fWrite.close();
sc.close();
Wow I've been using java for 10 years and have never heard of scanner!
It appears to use white space delimiters by default so you can't tell when an end of line occurs.
Looks like you can change the delimiters of the scanner - see the example at Scanner Class:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();

Categories