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
}
}
}
Related
In my high school comp sci class I have to read a text file with marks and then create an array with those marks in them (so I can manipulate them later). When I try and read the number of lines in the program it reads one less than there is, and when I output the array it consists of only "1.00" written to the amount of lines it has counted (which is incorrect).
import java.awt.*;
import java.io.*;
import hsa.Console;
public class Assignment3Q3
{
static Console c;
public static void main (String[] args) throws IOException
{
c = new Console ();
BufferedReader input = new BufferedReader (new FileReader ("marks.txt"));
String mark = input.readLine ();
int lines = 0;
while (input.readLine () != null)
lines++;
input.close ();
c.println (lines);
double[] marks = new double [lines];
int count = 0;
BufferedReader input1 = new BufferedReader (new FileReader ("marks.txt"));
while (input1.readLine () != null)
{
marks [count] = Double.parseDouble (mark);
count += 1;
if (count == lines)
{
break;
}
}
for (int x = 0 ; x < lines ; x++)
{
c.println (marks [x]);
}
}
}
In your second while loop, you are always assigning the parsed version of mark variable to the marks array elements. But you have only set mark variable once in your code, which is the first line of your file.
Anyway without reading the file twice (once to get the number of lines and then to store the actual line content), you can do this in a single read cycle by using a List instead of an array.
try (BufferedReader input = new BufferedReader (new FileReader("src/marks.txt"))) {
List<Double> marks = new ArrayList<>();
String line;
while ((line = input.readLine()) != null) {
marks.add(Double.parseDouble(line));
}
System.out.println(marks);
} catch (IOException e) {
e.printStackTrace();
}
In case you really want to get these marks to an array, you can onvert the above list into an array as follows.
Double[] marksArray = marks.toArray(new Double[marks.size()]);
Also as I have done in the above code snippet, better to use try with resources approach when you create AutoCloseable resources such as BufferedReader or FileReader. Then you don't have to close them explicitly in your code.
Why this separation in two steps at all? This is error prone. No values in the marks-array above the current line-count are accessed. So store the doubles in a dynamicly growing ArrayList<Double> instead and do the job in one step.
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.
This was the question asked: Write a program to read planet details from binary.txt using DataInputStream and print planet details on the standard output.
However, the program below throws an IOException. I can't figure out the problem. Any help would be appreciated.
import java.io.*;
public class LA4ex2b {
public static void main(String[] args) throws IOException {
DataInputStream input=null;
try
{
input= new DataInputStream(new FileInputStream("C:/Users/user/workspace/LA4ex2a/binary.txt"));
String str;
// read until the string read is null i.e. read till end of file
while ((str = input.readUTF()) != null) {
String token[] = str.split(" "); // tokenizes the string with
// space as a delimeter
for (int i = 0; i <token.length; i++)
{
if (IsDouble.IsaDouble(token[i]))
System.out.print(Double.parseDouble(token[i]));
else
System.out.print(token[i]);
}
}
}
catch (IOException e) {
e.printStackTrace();
}
finally
{
if (input!= null)
input.close();
}
}
}
if you're reading a binary file, you cannot assume it´s stored as text.
instead, you must know beforehand what are each field data type and read them like
DataInputStream input= new DataInputStream(new FileInputStream(new File("xyz")));
double d = input.readDouble();
int i = input.readInt();
char c = input.readChar();
As you can see there is "Mercury" - planet name - but no text representation of a double "1.23", so it is really binary data. Maybe input.readDouble? Always do an internet search for the javadoc.
I am creating a program that will produces the statistics of a baseball team
i am trying to create a constructor to read the file into the teamName instance variable and the battingAverages array.
the txt file contains the one word name of the team followed by 20 batting averages.
"Tars 0.592 0.427 0.194 0.445 0.127 0.483 0.352 0.190 0.335 0.207 0.116 0.387 0.243 0.225 0.401 0.382 0.556 0.319 0.475 0.279 "
I am struggling to find how to go about this and get it started?
I ran this and this might be close to what you want. Instead of making a confusing constructor, make a private method that the constructor will call to read in the file into the array.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Baseball {
private File textFile;
private Scanner input;
private String teamName;
//this will only work if you know there will be 20 entries everytime
//otherwise I recommend loading the data into an ArrayList
private double []battingAvgs = new double[20];
public Baseball(String file){
textFile = new File(file);
readInFile(textFile);
}
//private method that reads in the file into an array
private void readInFile(File textFile){
try {
input = new Scanner(textFile);
//read first string into variable teamName
teamName = input.next();
int i=0;
//iterate through rest of file adding it to an ArrayList
while(input.hasNext()){
battingAvgs[i] = input.nextDouble();
i++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//print out array
public void printArray(){
for(Double a: battingAvgs){
System.out.println(a);
}
}
}
Well, if these are all on one line in a specific file then what you could do is construct a bufferedreader to read the first line of your file, split the line based on spaces, and then parse the teamName and batting averages out.
BufferedReader br = new BufferedReader(new FileReader("myfile.txt"));
String[] line = br.readLine().split(" ");
br.close();
teamName = line[0];
battingAverages = new int[20];
for(int i = 0; i < 20; i++)
battingAverages[i] = Integer.parseInt(line[i+1]);
These might throw IOExceptions, which you will need to catch. I think Java 7 has a method to automatically handle these kinds of errors (not sure about this), but as I am new to Java 7's added functionality, I would just manually check for those exceptions.
You need to use the BufferedReader, FileInputStream, and InputStreamReader. Your file.txt should have the batting averages on every line, as shown below.
0.592
0.427
0.194
Here is an example of a class that when created, it will read a text file line by line and add each line to the array list:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Class {
ArrayList<Double> averages;
public Class() {
averages = new ArrayList<Double>();
try {
FileInputStream in = new FileInputStream("inputFile.txt"); //your file path/name
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine = br.readLine())!= null) averages.add(Double.parseDouble(strLine));
}catch(Exception e){
System.out.println(e);
}
}
}
Hope this helps
Try using the Scanner class.
File file=new File("TestFile.txt"); //Create a new file
Scanner scan=new Scanner(file);//Create a Scanner object (Throws FileNotFoundException)
if(scan.hasNext()) //Check to make sure that there is actually something in the file.
{
String line=scan.nextLine(); //Read the line of data
String[] array=line.split(" "); //Split line into the different parts
teamName=array[0]; //The team name is located in the first index of the array
battingAverages=new double[array.length-1];//Create a new array to hold the batting average values
for(int i=0;i<battingAverages.length;i++) //Loop through all of the averages
{
double average=Double.parseDouble(array[i+1]);//Convert the string object into a double
battingAverages[i]=average; //Add the converted average to the array
}
System.out.print(teamName+" "+Arrays.toString(battingAverages)); //[Optional] Print out the resulting values
}
import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
Above is the code I'm currently attempting to use, it compiles fine, then I get a runtime error of:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
I've googled the error and not had anything that helped (I only googled the first 3 lines of the error)
Basically, the program I'm writing is part of a bigger program. This part is to get information from a text file which is written like this:
Film one / 1.5
Film two / 1.3
Film Three / 2.1
Film Four / 4.0
with the text being the film title, and the float being the duration of the film (which will have 20 minutes added to it (For adverts) and then will be rounded up to the nearest int)
Moving on, the program is then to put the information in an array so it can be accessed & modified easily from the program, and then written back to the file.
My issues are:
I get a run time error currently, not a clue how to fix? (at the moment I'm just trying to read each line, and store it in an array, as a base to the rest of the program) Can anyone point me in the right direction?
I have no idea how to have a split at "/" I think it's something like .split("/")?
Any help would be greatly appreciated!
Zack.
Your code is working but it reads just one line .You can use bufferedReader here is an example import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And here is an split example class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
I wouldn't use a Scanner, that's for tokenizing (you get one word or symbol at a time). You probably just want to use a BufferedReader which has a readLine method, then use line.split("/") as you suggest to split it into two parts.
Lazy solution :
Scanner scan = ..;
scan.nextLine();