First of, I don't know how a.db file stores it data. If it does it in one line, or over many lines. Probably it does some difference from how to solve the problem.
the problem I'm facing is that I don't know how much data the file contains, only that it will be a date, time, and a description for x number of events in the form given below.
I have to convert the text into strings and put them in an array, but I don't know how to separate the text. When I tried I just ended up with one long string.
Can anybody help me?
01.01.2015|07:00-07:15|get up
01.01.2015|08:00|get to work
01.01.2015|08:00-16:00| work
01.01.2015|16:00-16:30| go home
what I want:
array[0] = "01.01.2015|07:00-07:15|get up"
array[1] = "01.01.2015|08:00|get to work"
array[2] = "01.01.2015|08:00-16:00| work"
array[3] = "01.01.2015|16:00-16:30| go home"
string table[] = new String [100];
void readFile(String fileName){
String read = "";
try {
x = new Scanner (new File(fileName));
}
catch (Exception e) {
}
while (x.hasNext()) {
read += x.nextLine();
}
}
Assuming here that your first code-block is in fact a copy of the file you're trying to read, you can do:
Scanner s = new Scanner(new File("file1.txt"));
List<String> lines = new LinkedList<>();
while (s.hasNextLine())
lines.add(s.nextLine());
If you really want to work with arrays and not lists, you can do
String[] table = lines.toArray(new String[lines.size()]);
after the loop.
If you're fortunate enough to work with Java 8, you can use:
List<String> lines = Files.lines(Paths.get("big.txt"))
.collect(Collectors.toList());
Again, if you really want to work with an array, you can convert the list using lines.toArray.
Since Java 8 you can use Paths.get(String first, String... more), Files.lines(Path path), and Stream.toArray():
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SOPlayground {
public static void main(String[] args) throws Exception {
Path path = Paths.get("/tmp", "db.txt");
Object[] lines = Files.lines(path).toArray();
System.out.println(lines.length);
System.out.println(lines[0]);
System.out.println(lines[lines.length - 1]);
}
}
Output:
4
01.01.2015|07:00-07:15|get up
01.01.2015|16:00-16:30| go home
Try this solution using arrays:
code
Scanner sc = new Scanner(new File("file.txt"));
int index;
String[] arr = new String[1];
for(index = 0; sc.hasNextLine(); index++) {
arr = Arrays.copyOf(arr, index + 1);
arr[index] = sc.nextLine();
}
for(int i = 0; i<arr.length; i++) {
System.out.print(arr[i] + "\n");
}
I have used arr = Arrays.copyOf(arr, index + 1) to increase the size of the array to add next element.
Output
01.01.2015|07:00-07:15|get up
01.01.2015|08:00|get to work
01.01.2015|08:00-16:00| work
01.01.2015|16:00-16:30| go home
Well, it took me some houres. Thanx to all who lended a hand. This was what I got in the end.
int i=0;
String array [] new String [100]
try {
FileReader textFileReader= new FileReader (fileName);
BufferedReader textReader= new BufferedReader(textFileReader);
boolean continue = true;
while (continue) {
String text = textReader.readLine();
if (text != null){
array[i] = text;
i++;
}else {
continue = false;
}
}
}catch (Exception e) {}
Related
I'm trying to read a file called "CityData.txt" that just has a list of city names in it, one on each line. I've been using scanner in the past to read Strings from a file, and am using it to read ints from another file in this same program, however it doesn't seem to be reading anything from the file.
int counter2 = 0;
File strFile = new File("CityData.txt");
Scanner strScanner = new Scanner(strFile);
Scanner strCountScanner = new Scanner(strFile);
while ((strScanner.hasNext() == true)) {
System.out.println(strScanner.nextLine());
counter2++;
}
System.out.println("This is counter2: " + counter2);
String[] array2 = new String[counter2];
while ((strCountScanner.hasNext() == true)) {
for (int i = 0; i < counter2; i++) {
array2[i] = strCountScanner.nextLine();
}
}
Ideally, counter2 will tell me how many cities are in the file, and I'll then populate array2 with them. However, counter2 remains at 0 after the program has been run. I've been fiddling with this for a while, and am hoping that maybe I've just missed something silly.
Thanks
You are trying to add cities to an array?
public static void readText throws FileNotFoundException {
ArrayList lines = new ArrayList();
Scanner scan = new Scanner(new File("CityData.txt"));
while(scan.hasNextLine()){
String line = scan.nextLine();
lines.add(line);
}
}
or a stream in 8
Stream <String> lines = Files.lines(Paths.get("c:\\demo.txt"));
lines.forEach(System.out::println);
lines.close();
Ideally I would avoid two loops and just use an ArrayList for this purpose. This can give you count as well as the flexibility to make the array more dynamic. Also I would enclose Scanner in try with resources block as it closes the resource itself. Here is the code for reference.
File strFile = new File("CityData.txt");
try (Scanner strScanner = new Scanner(strFile)) {
ArrayList<String> arrayList = new ArrayList<>();
while (strScanner.hasNext()) {
arrayList.add(strScanner.nextLine());
}
System.out.println("number of cities is " + arrayList.size());
System.out.println("cities are " + arrayList);
}catch (Exception e){
e.printStackTrace();
}
Since you are reading in string, using hasNextLine() will be more appropriate. You can try the code below, it should work as intended. HTH.
int counter2 = 0;
File strFile = new File("CityData.txt");
Scanner strScanner = new Scanner(strFile);
Scanner strCountScanner = new Scanner(strFile);
while((strScanner.hasNextLine() == true)) {
System.out.println(strScanner.nextLine());
counter2++;
}
System.out.println("This is counter2: " + counter2);
String[] array2 = new String[counter2];
while((strCountScanner.hasNextLine() == true)) {
for (int i = 0; i < counter2; i++) {
array2[i] = strCountScanner.nextLine();
}
}
I have a problem wrtting the code for comparing two files (first reference file):
PROTOCOL STATE SERVICE
1 open icmp
6 open tcp
17 open udp
and (execution file)
PROTOCOL STATE SERVICE
1 open icmp
6 open tcp
17 open udp
255 closed unknown
and save difference between these two files in new file (255 closed unknown).
For comparing I have used following code but it seems it doesn't work.
public String[] compareResultsAndDecide(String refFile, String execFile) throws IOException {
String[] referenceFile = parseFileToStringArray(refFile);
String[] execCommand = parseFileToStringArray(execFile);
List<String> tempList = new ArrayList<String>();
for(int i = 1; i < execCommand.length ; i++)
{
boolean foundString = false; // To be able to track if the string was found in both arrays
for(int j = 1; j < referenceFile.length; j++)
{
if(referenceFile[j].equals(execCommand[i]))
{
foundString = true;
break; // If it exist in both arrays there is no need to look further
}
}
if(!foundString) // If the same is not found in both..
tempList.add(execCommand[i]); // .. add to temporary list
}
String diff[] = tempList.toArray(new String[0]);
if(diff != null) {
return diff;
}
For String refFile I would use /home/xxx/Ref.txt path to reference file. And the same for execFile (second file shown up).
Anyone can help me with this?
Just to add, I'm using for parsing File to String Array:
public String[] parseFileToStringArray(String filename) throws FileNotFoundException {
Scanner sc = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = lines.toArray(new String[0]);
return arr;
}
Change int i = 1 to int i = 0 and int j = 1 to int j = 0
your compareResultsAndDecide method has to be changed like :
public static String[] compareResultsAndDecide(String refFile, String execFile) throws IOException {
String[] referenceFile = parseFileToStringArray(refFile);
String[] execCommand = parseFileToStringArray(execFile);
List<String> tempList = new ArrayList<String>();
List<String> diff = new ArrayList(Arrays.asList(execCommand));
diff.removeAll(Arrays.asList(referenceFile));
String[] toReturn = new String[diff.size()];
toReturn = diff.toArray(toReturn);
return toReturn;
}
and your parseFileToStringArray like:
public String[] parseFileToStringArray(String filename) throws FileNotFoundException {
Scanner sc = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = new String[lines.size()];
return lines.toArray(arr);
}
Problem is in your .txt files. Your encoding must be different.
I know this isn't the best way, but if you use replaceAll() method to replace white spaces from your lines of text files, your code should work. But Unfortunately, you will miss the spaces between lines.
Change:
String[] arr = lines.toArray(new String[0]);
To:
String[] arr = lines.toArray(new String[0]).replaceAll(" ", "");
Note:
I tried using trim() but it didn't worked well for me.
As I mentioned above, array elements starts from 0, not from 1. Change that too.
For now in my program i am using hard-coded values, but i want it so that the user can use any text file and get the same result.
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
public class a1_12177903
{
public static void main(String [] args) throws IOException
{
if (args[0] == null)
{
System.out.println("File not found");
}
else
{
File file = new File(args[0]);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
while (br.ready())
{
line += br.readLine();
}
String[] work = line.split(",");
double[] doubleArr = new double[work.length];
for (int i =0; i < doubleArr.length; i++)
{
doubleArr[i] = Double.parseDouble(work[i]);
}
double maxStartIndex=0;
double maxEndIndex=0;
double maxSum = 0;
double total = 0;
double maxStartIndexUntilNow = 0;
for (int currentIndex = 0; currentIndex < doubleArr.length; currentIndex++)
{
double eachArrayItem = doubleArr[currentIndex];
total += eachArrayItem;
if(total > maxSum)
{
maxSum = total;
maxStartIndex = maxStartIndexUntilNow;
maxEndIndex = currentIndex;
}
if (total < 0)
{
maxStartIndexUntilNow = currentIndex;
total = 0;
}
}
System.out.println("Max sum : "+ maxSum);
System.out.println("Max start index : "+ maxStartIndex);
System.out.println("Max end index : " +maxEndIndex);
}
}
}
I've fixed it so it takes in the name of the text file from the command line. if anyone has any ways to improve this, I'll happily accept any improvments.
You can do this with Java8 Streams, assuming each entry has it's own line
double[] doubleArr = Files.lines(pathToFile)
.mapToDouble(Double::valueOf)
.toArray();
If you were using this on production systems (rather than as an exercise) it would be worth while to create the Stream inside a Try with Resources block. This will make sure your input file is closed properly.
try(Stream<String> lines = Files.lines(path)){
doubleArr = stream.mapToDouble(Double::valueOf)
.toArray();
}
If you have a comma separated list, you will need to split them first and use a flatMap.
double[] doubleArr = Files.lines(pathToFile)
.flatMap(line->Stream.of(line.split(","))
.mapToDouble(Double::valueOf)
.toArray();
public static void main(String[] args) throws IOException {
String fileName = "";
File inputFile = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(inputFile));
// if input is in single line
StringTokenizer str = new StringTokenizer(br.readLine());
double[] intArr = new double[str.countTokens()];
for (int i = 0; i < str.countTokens(); i++) {
intArr[i] = Double.parseDouble(str.nextToken());
}
// if multiple lines in input file for a single case
String line = "";
ArrayList<Double> arryList = new ArrayList<>();
while ((line = br.readLine()) != null) {
// delimiter of your choice
for (String x : line.split(" ")) {
arryList.add(Double.parseDouble(x));
}
}
// convert arraylist to array or maybe process arrayList
}
This link may help: How to use BufferedReader. Then you will get a String containing the array.
Next you have several ways to analyze the string into an array.
Use JSONArray to parse it. For further information, search google for JSON.
Use the function split() to parse string to array. See below.
Code for way 2:
String line="10,20,50";//in fact you get this from file input.
String[] raw=line.split(",");
String[] arr=new String[raw.length];
for(int i=0;i<raw.length;++i)arr[i]=raw[i];
//now arr is what you want
Use streams if you are on JDK8. And please take care of design principles/patterns as well. It seems like a strategy/template design pattern can be applied here. I know, nobody here would ask you to focus on design guidelines.And also please take care of naming conventions. "File" as class name is not a good name.
Ok. So I am working on a program that gets information that has been put into textfields in a gui and puts that information into a text file and the name of the file is the name of the animal and name of the owners last name.
//that part is done.
Then able to search for the file using the name of the animal and the owners last name, and being able to have the information be put into separate text fields. That look like the page where you first put down the information. Then being able to save the information changed to the same text file.
Now my question is how do I get the information from a text file that has different lines and then put each line in its own String.
Here is the part of the program that reads the text file
`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 = 20;
String[] textData = new String[numberOfLines];
int i;
for (i=0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
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;
}
}
`
// Here is where I am using this code
`JButton b7 = new JButton("Done");
b7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f4.setVisible(true);
f3.setVisible(false);
scrollPane.revalidate();
scrollPane.repaint();
String namess = names.getText();
na.setText(namess);
String ownerslss = ownersls.getText();
ol.setText(ownerslss);
String file_name =namess + " " + ownerslss + ".txt";
na.setText(namess);
ol.setText(ownerslss);
try {
ReadFile file = new ReadFile (file_name);
String [] aryLines = file.OpenFile();
String aryLiness ="";
int item, space;
for (item=0; item < aryLines.length; item++) {
System.out.println(aryLines[item]);
aryLiness = Arrays.toString(aryLines);
space = aryLines.length;
}
space = aryLines.length;
//< assname is a textarray that is the only way I could get the words to go down the page but it doesn't look good at all. Because it doesn't skip lines...
assname.setSize(20 ,space);
assname.append("" + aryLiness);
panimals.add(assname);
}
catch (IOException wewe) {
System.out.println(wewe.getMessage() );
}
}
});`
It's important to know how arrays work, because they are used very often.
String[] myStringArray = new String[3];
This array holds 3 String objects. It is essentially the same as if you had done:
String oneString = null; //same as myStringArray[0]
String twoString = null; //same as myStringArray[1]
String threeString = null;//same as myStringArray[2]
This means, after you read all your lines into Strings, you can create your JTextField like so:
JTextField myTextField1 = new JTextField(myStringArray[0]);
JTextField myTextField2 = new JTextField(myStringArray[1]);
JTextField myTextField3 = new JTextField(myStringArray[2]);
or, assigning an array one line at a time:
JTextField[] myTextFields = new JTextField[3];
myTextFields[0] = new JTextField(myStringArray[0]);
myTextFields[1] = new JTextField(myStringArray[1]);
myTextFields[2] = new JTextField(myStringArray[2]);
Now, imagine if you had 300 Strings and TextFields, there's no way you would want to type those lines 300 times. That's why for loops are awesome.
JTextField[] myTextFields = new JTextField[300];
for (int i = 0; i < myTextFields.length; i++)
{
myTextFields[i] = new JTextField(myStringArray[i]);
}
Not sure if you realize, but you currently read every line in your textfile into an array already, named aryLines. You then print each String individually in your for loop:
System.out.println(aryLines[item]); //item is starting at 0, goes through every String
aryLines[0] is your first string. aryLines[1] is your second.. and so on until the last line. Theoretically, you could create a BufferedWriter like shown here and completely copy your current textfile into a new one just doing basically what you are already doing. You would just use this instead of the System.out.println() after creating your BufferedWriter:
writer.write(aryLines[item]);
writer.newLine();
After you print out every line to the console, I'm not sure what you mean to do. aryLiness with two ss is created by combining all the Strings in your array into one String. Then you set your TextArray with the entire combined String.
I am trying to create a matrix from a text file. The problem is that when the Buffered Reader function readline() is done parsing first line of file it comes to second line but the its reading it as empty which it is not.
void covar()
{
double [][]covar=new double[10][5];
int i=0;
int j=0;
try
{
FileInputStream fstream = new FileInputStream("class 1\\feature_vector.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String input;
while((input=br.readLine())!= null)
{
String [] temp=input.split(",");
//System.out.println(input.split(",").length);
covar[i][j]= new Double(temp[0]);
covar[i+1][j]=new Double(temp[1]);
covar[i+2][j]=new Double(temp[2]);
covar[i+3][j]=new Double(temp[3]);
covar[i+4][j]=new Double(temp[4]);
//i=0;
j++;
}
in.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Above is the code. The file name is perfect and nothing is wrong with the stream thing. Can you guys help me out with what is wrong with this.
Here is the content of the file:
0.75,321.0,0.22429906,0.97507787,1.966202512778112
0.33333334,135.0,-0.014814815,1.0,5.323770568766052
0.64285713,311.0,0.025723472,1.0,4.764298570227433
0.6,188.0,0.03723404,1.0,4.7349608150168105
0.25,189.0,0.16931216,0.98941797,7.15681209803803
0.71428573,194.0,-0.26804122,0.96391755,5.1654456838422425
0.6,173.0,0.028901733,1.0,6.54275787030257
0.2857143,257.0,0.031128405,1.0,6.095356508899233
0.23076923,197.0,-0.04568528,1.0,3.784908227189768
0.18181819,231.0,0.17316018,0.987013,5.956322938602553
There are two things that are obviously wrong:
You do not need variable i, because one of the dimensions is fixed, and you "unrolled" the loop five times
You swapped the indexes: j should go first, that's the one changing from 0 to 9.
For example:
String [] temp=input.split(",");
covar[j][0] = new Double(temp[0]);
covar[j][1] =new Double(temp[1]);
covar[j][2] =new Double(temp[2]);
covar[j][3] =new Double(temp[3]);
covar[j][4] =new Double(temp[4]);
You could put the loop back to shorten your code:
String [] temp=input.split(",");
for (int i = 0 ; i != 5 ; i++) {
covar[j][i] = new Double(temp[i]);
}
It looks like you are using the wrong indicies for you matrix, I think it should be something like this:
int i = 0;
while((input=br.readLine())!= null) {
String [] temp=input.split(",");
//System.out.println(input.split(",").length);
covar[i][0]= new Double(temp[0]);
covar[i][1]=new Double(temp[1]);
covar[i][2]=new Double(temp[2]);
covar[i][3]=new Double(temp[3]);
covar[i][4]=new Double(temp[4]);
++i;
}
Your file might have some strange line-terminators that are making the reader think there is an extra line.
You can try to just make your code skip blank lines:
while((input=br.readLine())!= null) {
if( input.length() > 0 ){
String [] temp=input.split(",");
for (int i = 0 ; i != 5 ; i++) {
covar[j][i] = new Double(temp[i]);
}
}
++j;
}