I’m trying to print out the result from the readline method in a certain format. I also need to add two more if statements, but I’m not sure how to get the code to continue through them if the previous one is true.
public static void main(String[] args) {
String csvFile = args[0]; //name of our csv file
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
String[] columns = new String[6];
String columnLine = "";
float notToBeBelow = 12;
try {
br = new BufferedReader(new FileReader(csvFile));
if ((columnLine = br.readLine()) != null) {
columns = columnLine.split(cvsSplitBy);
while ((line = br.readLine()) != null) {
// use comma as separator
String[] routerInfo = line.split(cvsSplitBy);
if (routerInfo[2].toLowerCase().equals("no")) {
float OSVersion = Integer.parseInt(routerInfo[3]);
if(OSVersion >= 12) {
}
}
You can do the following:
if (condition) {
} else {
if (condition2) {}
else {}
if (condition3) {}
else {}
}
You can place an if inside the else of another one.
Related
Have a two text file with words list. need save both file in two array.I know how to do it using list and set.. but here I want know how to do it using only arrays.Only array and no predefined functions such as Arrays.sort() or Collections.sort() can be used
no list no ArrayList or no class from Java Collection Frameworks can be used.
public class Main {
public static Set<String> setlist1= new HashSet<>();
public static String[] arrayList=new String[file1count];
public static String[] array2=new String[file2count];
public static int file1count=0;
public static int file2count=0;
public static void main(String[] args) {
try {
/*read the files*/
Scanner rf= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt")));
Scanner rf2= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt")));
String line;
String line2;
while(rf.hasNext()){
line=rf.nextLine();
file1count++;
}
while(rf2.hasNext()){
line2=rf2.nextLine();
file2count++;
}
rf.close();
rf2.close();
}catch(IOException e){
System.out.println(e);
}
}
}
The problem with using arrays is that you don't know in advance what length to allocate.
You basically have two options:
read each file twice
allocate an array of some initial length, and reallocate is as needed (that's what an ArrayList does.)
Second option: let's have a method readFile that reads all the lines from a file and returns an array:
public static String[] readFile(String fileName) throws IOException {
try (Reader reader = new FileReader(fileName);
BufferedReader in = new BufferedReader(reader)) {
String[] lines = new String[10]; // start with 10
int count = 0;
String line;
while ((line = in.readLine()) != null) {
if (count >= lines.length) {
lines = reallocate(lines, count, 2*lines.length);
}
lines[count++] = line;
}
if (count < lines.length) {
// reallocate to the final length;
lines = reallocate(lines, count, count);
}
return lines;
}
}
private static String[] reallocate(String[] lines, int count,
int newLength) {
String[] newArray = new String[newLength];
for (int i = 0; i < count; ++i) {
newArray[i] = lines[i];
}
lines = newArray;
return lines;
}
BufferedReader reader1 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt"));
BufferedReader reader2 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt"));
String line1 = reader1.readLine();
String[] array1 = new String[10000000];
String[] array2 = new String[10000000];
String line2 = reader2.readLine();
boolean areEqual = true;
int lineNum = 1;
while (line1 != null || line2 != null) {
if (line1 == null || line2 == null) {
areEqual = false;
break;
} else if (!line1.equalsIgnoreCase(line2)) {
areEqual = false;
break;
}
if (line1 != null) {
array1[lineNum] = line1;
}
if (line1 != null) {
array2[lineNum] = line2;
}
line1 = reader1.readLine();
line2 = reader2.readLine();
lineNum++;
}
if (areEqual) {
System.out.println("Same content.");
} else {
System.out.println("different content");
}
reader1.close();
reader2.close();
You can simply try above code.
Here I had used only WHILE loop, BufferedReader and FileReader.
I'm writing a code where I've to read current line and next line. If next line contains some string, I need to delete current line.
But when I do it, once it reaches the EOF, it is showing me null pointer exception.
Below is my code.
private static void cleanUpTempFile(File temp) throws IOException {
FileReader fr = new FileReader(temp);
BufferedReader temp_in = new BufferedReader(fr);
String tempStr, tempStr1 = null;
int i = 0;
for (String next, footnotes = temp_in.readLine(); footnotes != null; footnotes = next) {
next = temp_in.readLine();
try {
if (next.contains("pb") && (next != null)) {
tempStr = footnotes;
tempStr1 = tempStr;
tempStr = tempStr1.replace(tempStr1, "");
footnotes = tempStr;
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println(footnotes);
}
temp_in.close();
}
It is throwing me error since when it comes since, when it comes to end, current line is showing last line and next points to next line which is null. How can I sort this.
Also, whenever there is a replace done, and empty line is created, Is there a way that I can stop creating a new line.
I tried adding the below code in my if
tempStr1 = tempStr;
footnotes = tempStr1.replace("\\s", "");
But this doesn't seem working.
Tried with the below code and my console prints null.
private static void cleanUpTempFile(File temp) throws IOException {
FileReader fr = new FileReader(temp);
BufferedReader temp_in = new BufferedReader(fr);
String tempStr, tempStr1 = null;
String footnotes;
while ((footnotes = temp_in.readLine()) != null) {
String next;
while ((next = temp_in.readLine()) != null) {
if (next.contains("pb")) {
tempStr = footnotes;
tempStr1 = tempStr;
tempStr = tempStr1.replace(tempStr1, "");
footnotes = tempStr;
}
}
}
System.out.println(footnotes);
temp_in.close();
}
Thanks.
As suggested by Baldurian you can check this by using Scanner#hasNextLine():
Scanner input = new Scanner(new File(filename));
String prevLine = input.nextLine();
while(input.hasNextLine())
{
String nextLine = input.nextLine();
//do some stuff
prevLine = nextLine;
}
Along with checking if the file exists and appending to it if so you should also have a .hasNextLine() conditional.
I'm trying to read data from a text file and create Item Objects with it.
Item Objects have fields String title, String formatt, boolean onLoan, String loanedTo and String dateLoaned. In my save()method, I print every object to a text file in a new line and the fields are seperated by "$" (dollar sign). How can I read the text file line by line and create a new object from each line and add it to an array.
TextFile Example:
StarWars$DVD$false$null$null
Aliens$Bluray$true$John$Monday
public void save() {
String[] array2 = listForSave();
PrintWriter printer = null;
try {
printer = new PrintWriter(file);
for (String o : array2) {
printer.println(o);
}
printer.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
public void open(){
try{
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
}catch ( IOException e ) {
e.printStackTrace();
}
}
Thanks everyone. Here's my final code:
public void open(){
try{
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
String[] strings;
while ((line = bufferedReader.readLine()) != null) {
strings = line.split("\\$");
String title = strings[0];
String format = strings[1];
boolean onLoan = Boolean.parseBoolean(strings[2]);
String loanedTo = strings[3];
String dateLoaned = strings[4];
MediaItem superItem = new MediaItem(title,format, onLoan,loanedTo,dateLoaned);
items.add(superItem);
}
fileReader.close();
}catch ( IOException e ) {
e.printStackTrace();
}
}
String line = // input line e.g. "Aliens$Bluray$true$John$Monday"
String[] strings = line.split("\\$"); // use regex matching "$" to split
String title = strings[0];
String formatt = strings[1];
boolean onLoan = Boolean.parseBoolean(strings[2]);
String loanedTo = strings[3];
String dateLoaned = strings[4];
// TODO: create object from those values
Maybe you need to handle null differently (in case you want the String "null" to be converted to null); note that you can't distinguish if null or "null" was saved.
This function converts "null" to null and returns the same string otherwise:
String convert(String s) {
return s.equals("null") ? null : s;
}
Reading the objects to an array
Since you don't know the number of elements before reading all lines, you have to work around that:
Write the number of objects in the file as first line, which would allow you to create the array before reading the first object. (Use Integer.parseInt(String) to convert the first line to int):
public void save() {
String[] array2 = listForSave();
PrintWriter printer = null;
try {
printer = new PrintWriter(file);
printer.println(array2.length);
for (String o : array2) {
printer.println(o);
}
printer.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
public void open(){
try{
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
int arraySize = Integer.parseInt(stringBuffer.readLine());
Object[] array = new Object[arraySize];
int index = 0;
String line;
while ((line = bufferedReader.readLine()) != null) {
// split line and create Object (see above)
Object o = // ...
array[index++] = o;
}
//...
}catch ( IOException e ) {
e.printStackTrace();
}
//...
}
or
Use a Collection, e.g. ArrayList to store the objects and use List.toArray(T[]) to get an array.
quick and dirty solution might be...
public void open(){
try{
ArrayList<Item> list = new ArrayList<Item>(); //Array of your ItemObject
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
Item itm = new Item(); //New Item Object
String [] splitLine = line.split("\\$");
item.title = splitLine[0];
item.format = splitLine[1];
item.onLoan = Boolean.parseBoolean(splitLine[2]);
item.loanedTo = splitLine[3];
item.dateLoaned = splitLine[4];
list.add(itm);
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
}catch ( IOException e ) {
e.printStackTrace();
}
}
But this is won't scale if you need to re-arrange or add new fields.
You could try this to "parse" every line of your file
String[] result = "StarWars$DVD$false$null$null".split("\\$");
for (int i=0; i<result.length; i++) {
String field = result[i]
... put the strings in your object ...
}
I am trying to read a text file in java using FileReader and BufferedReader classes. Following an online tutorial I made two classes, one called ReadFile and one FileData.
Then I tried to extract a small part of the text file (i.e. between lines "ENTITIES" and "ENDSEC"). Finally l would like to tell the program to find a specific line between the above-mentioned and store it as an Xvalue, which I could use later.
I am really struggling to figure out how to do the last part...any help would be very much apprciated!
//FileData Class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main (String[] args) throws IOException {
String file_name = "C:/Point.txt";
try {
ReadFile file = new ReadFile (file_name);
String[] aryLines = file.OpenFile();
int i;
for ( i=0; i < aryLines.length; i++ ) {
System.out.println( aryLines[ i ] ) ;
}
}
catch (IOException e) {
System.out.println(e.getMessage() );
}
}
}
// ReadFile Class
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.lang.String;
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 = readLines();
String[] textData = new String[numberOfLines];
String nextline = "";
int i;
// String Xvalue;
for (i=0; i < numberOfLines; i++) {
String oneline = textReader.readLine();
int j = 0;
if (oneline.equals("ENTITIES")) {
nextline = oneline;
System.out.println(oneline);
while (!nextline.equals("ENDSEC")) {
nextline = textReader.readLine();
textData[j] = nextline;
// xvalue = ..........
j = j + 1;
i = i+1;
}
}
//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;
}
}
I don't know what line you are specifically looking for but here are a few methods you might want to use to do such operation:
private static String START_LINE = "ENTITIES";
private static String END_LINE = "ENDSEC";
public static List<String> getSpecificLines(Srting filename) throws IOException{
List<String> specificLines = new LinkedList<String>();
Scanner sc = null;
try {
boolean foundStartLine = false;
boolean foundEndLine = false;
sc = new Scanner(new BufferedReader(new FileReader(filename)));
while (!foundEndLine && sc.hasNext()) {
String line = sc.nextLine();
foundStartLine = foundStartLine || line.equals(START_LINE);
foundEndLine = foundEndLine || line.equals(END_LINE);
if(foundStartLine && !foundEndLine){
specificLines.add(line);
}
}
} finally {
if (sc != null) {
sc.close();
}
}
return specificLines;
}
public static String getSpecificLine(List<String> specificLines){
for(String line : specificLines){
if(isSpecific(line)){
return line;
}
}
return null;
}
public static boolean isSpecific(String line){
// What makes the String special??
}
When I get it right you want to store every line between ENTITIES and ENDSEC?
If yes you could simply define a StringBuffer and append everything which is in between these to keywords.
// This could you would put outside the while loop
StringBuffer xValues = new StringBuffer();
// This would be in the while loop and you append all the lines in the buffer
xValues.append(nextline);
If you want to store more specific data in between these to keywords then you probably need to work with Regular Expressions and get out the data you need and put it into a designed DataStructure (A class you've defined by our own).
And btw. I think you could read the file much easier with the following code:
BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));
try {
while ((line = reader.readLine()) != null) {
if(line.equals("ENTITIES") {
...
}
} (IOException e) {
System.out.println("IO Exception. Couldn't Read the file!");
}
Then you don't have to read first how many lines the file has. You just start reading till the end :).
EDIT:
I still don't know if I understand that right. So if ENTITIES POINT 10 1333.888 20 333.5555 ENDSEC is one line then you could work with the split(" ") Method.
Let me explain with an example:
String line = "";
String[] parts = line.split(" ");
float xValue = parts[2]; // would store 10
float yValue = parts[3]; // would store 1333.888
float zValue = parts[4]; // would store 20
float ... = parts[5]; // would store 333.5555
EDIT2:
Or is every point (x, y, ..) on another line?!
So the file content is like that:
ENTITIES POINT
10
1333.888 // <-- you want this one as xValue
20
333.5555 // <-- and this one as yvalue?
ENDSEC
BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));
try {
while ((line = reader.readLine()) != null) {
if(line.equals("ENTITIES") {
// read next line
line = reader.readLine();
if(line.equals("10") {
// read next line to get the value
line = reader.readLine(); // read next line to get the value
float xValue = Float.parseFloat(line);
}
line = reader.readLine();
if(line.equals("20") {
// read next line to get the value
line = reader.readLine();
float yValue = Float.parseFloaT(line);
}
}
} (IOException e) {
System.out.println("IO Exception. Couldn't Read the file!");
}
If you have several ENTITIES in the file you need to create a class which stores the xValue, yValue or you could use the Point class. Then you would create an ArrayList of these Points and just append them..
I want map my object from text file, the text file contents are like this :
~
attribute1value
attribute2value
attribute3value
attribute4value
attribute5value
attribute6value
~
attribute1value
attribute2value
attribute3value
attribute4value
attribute5value
attribute6value
...continued same
So for each 5 attributes I want to create new object and map those 6 properties to it(that is not issue), the issue is how can I distinguish lines while reading, how can I get the first group, second group etc . thank you
I suggest using a 3rd-party utility such as Flatworm to handle this for you.
Adapted from here, and assuming there are always 6 properties per object:
You can use java.io.BufferedReader to read a file line by line.
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
int count = 0;
MyObject obj = null;
while ((line = reader.readLine()) != null) {
if(obj == null) obj = new MyObject();
if(count <= 6) {
switch(count) {
case 0: // ignore: handles '~'
break;
case 1: // assign value of line to first property, like:
obj.prop1 = line;
break;
// etc up to case 6
}
count++;
} else {
// here, store object somewhere, then...
obj = null;
count = 0;
}
}
Here is a more flexible approach. We can specify a custom (single-line) delimiter, no delimiter is actually needed at the beginning or at the end of the file (but can be given), the number of lines of a record is flexible. The data is parsed into a simple model which can be used to validate data and create the final objects.
private String recordDelimiter = "~";
public static List<List<String>> parse(Reader reader) {
List<List<String>> result = new ArrayList<List<String>>();
List<String> record = new ArrayList<String>();
boolean isFirstLine = true;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.length() == 0) {
continue; // we skip empty lines
}
if (delimiter.equals(line.trim()) {
if (!isFirstLine) {
result.add(record);
record = new ArrayList<String>();
} else {
isFirstLine = false; // we ignore a delimiter in the first line.
}
continue;
}
record.add(line);
isFirstLine = false;
}
if (!result.contains(record))
result.add(record); // in case the last line is not a separator
return result;
}
Primitive code, no exception handling, requires 100% perfect file structure and file which ends in the record delimiter character '~'.
Gives you a start though.
public class Record {
private String field1 = null;
private String field2 = null;
private String field3 = null;
private String field4 = null;
private String field5 = null;
private String field6 = null;
private void read(DataInputStream din) throws IOException, ClassNotFoundException {
BufferedReader reader = new BufferedReader(new InputStreamReader(din));
field1 = reader.readLine();
field2 = reader.readLine();
field3 = reader.readLine();
field4 = reader.readLine();
field5 = reader.readLine();
field6 = reader.readLine();
reader.readLine(); // Skip separator line "~".
}
private static void main(String[] args) throws IOException, ClassNotFoundException {
FileInputStream fin = new FileInputStream("C:\\file.dat");
DataInputStream din = new DataInputStream(fin);
Collection<Record> records = new LinkedList<Record>();
while(0 < din.available()) {
Record record = new Record();
record.read(din);
records.add(record);
}
}
}