Read only values from aText file - java

I've a text file which has values given as =
FORMNAME1=Cat
CONTROL ID=6
DATA WIDTH=20
LABEL WIDTH = 30
LABEL ALIGN = R
FORMNAME2= bat
CONTROL ID=5
DATA WIDTH=20
LABEL WIDTH = 30
LABEL ALIGN = R
FORMNAME3= rat
CONTROL_ID3=10
DATAWIDTH3=20
LABELWIDTH3 = 30
LABEL_ALIGN3 = R
How to read only the values stored in each line i.e only the data after = using JAVA?

Read the file as shown here, and use String.split() in each line to get the value:
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String value = line.split("=")[1];
System.out.println(value);
}
}
EXPLANATION: to read the file, is well explained in question I linked
lets see: you are processing each line of the file INDIVIDUALLY, then the content of the file (just one line) arrives to this part of the code, but what is doing this line?
String value = line.split("=")[1];
line variable, in first iteration will contain:
FORMNAME1=Cat
split("=") will create an array like this
[0] FORMNAME1
[1] Cat
so the line is assigning the value of position 1 (Cat) to the variable value
String value = "Cat";
Second iteration will do same but different content:
line = "CONTROL ID=6"
so
line.split("=")
will result
[0] CONTROL ID
[1] 6
And
// be careful is a string representing "6"
// not the numerical value 6 as int or double!!!!!
String value = "6";
and so on....
EXTRA TIP:
use String.valueOf() if you want to extract numerical values

Related

BufferedReader - Output columns in in different order JAVA

I have 2 csv files with column 'car', 'bike', 'tractor' etc
The below code prints out data from the csv which works fine, however cvs 1 prints out in a different or to csv 2 so I want to arrange the columns in a different order.
From this code, how can I organise the data to print out in order of which column I want first, second etc.
BufferedReader r = new BufferedReader(new InputStreamReader(str));
Stream lines = r.lines().skip(1);
lines.forEachOrdered(
line -> {
line= ((String) line).replace("\"", "");
ret.add((String) line);
The columns print out like this:
csv 1
Car, Bike, Tractor, Plane, Train
csv 2
Bike, Plane, Tractor, Train, Car,
but I want to manipulate the code so the two csv files print out in the same order like;
Bike, Plane ,Tractor, Train, Car
I can't use the likes of col[1],col[3], as the two files are in different or so I would need to call them by column name in the csv file so col["Truck"] etc
Or is there another way. Like creating a new list from the csv 1 output and rearranging ?
I haven't used BufferedReader much so I'm not sure if this is a silly question and there's a simple solution
A BufferedReader reads lines, and does not care for the content of those lines. So this code will simply save lines into ret as it is reading them:
List<String> ret = new ArrayList<>();
try (BufferedReader r = new BufferedReader(new InputStreamReader(str))) {
r.lines().skip(1).forEachOrdered(l -> ret.add(l.replace("\"", ""));
}
// now ret contains one string per CSV line, excluding the 1st
(This is somewhat better than your code in that it is guaranteed to close the reader correctly, and does not require any casts to string).
If your CSV lines do not contain any , characters that are not separators, you can modify the above code to split lines into columns; which you can then reorder:
List<String[]> ret = new ArrayList<>(); // list of string arrays
try (BufferedReader r = new BufferedReader(new InputStreamReader(str))) {
r.lines().skip(1).forEachOrdered(l ->
ret.add(l.replace("\"", "").split(",")); // splits by ','
}
// now ret contains a String[] per CSV line, skipping the 1st;
// with ret.get(0)[1] being the 2nd column of the 1st non-skipped line
// this will output all lines, reversing the order of columns 1 and 2:
for (String[] line : ret) {
System.out.print(line[1] + ", " + line[0]);
for (int i=2; i<line.length; i++) System.out.print(", " + line[i]);
System.out.println();
}
If your CSV lines can contain ,s that are not delimiters, you will need to learn how to correctly parse (=read) CSVs, and that requires significantly more than a BufferedReader. I would recommend using an external library to handle this correctly (for there are many types of CSVs in the wild). In particular, using Apache Commons CSV, things are relatively straightforward:
try (Reader in = new FileReader("path/to/file.csv")) {
Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
for (CSVRecord record : records) {
String columnOne = record.get(0);
String columnTwo = record.get(1);
}
}

Java, CSV, Getting error if do not click on Save button of the csv file

This is my code
public double myMethod(String name)
{
double result = 0.0;
String path = "/Users/T/Desktop/Training/MyFolder/";
int maxColumn = 0;
BufferedReader br = null;
ArrayList findMaxColumn = new ArrayList();
String line = "";
try
{
br = new BufferedReader(new FileReader(path+name));
while((line = br.readLine())!= null)
{
findMaxColumn.add(temp.split(",").length);
}
maxColumn = getMaxNumber(findMaxColumn);
CSVReader reader = new CSVReader(new FileReader(path+name));
List<String[]> myData = reader.readAll();
for(int i = 0 ; i < maxColumn;i++)
{
for (String[] lineData : myData)
{
String value= lineData[i];
The problem is, I have a csv file (generated from other method and stored in MyFolder) and when I run this code, I got an error "ArrayIndexOutOfBoundsException: 1" at String value= lineData[i]. But, if I open my csv file and click on save button (or make some changes for a value eg 0 to 1 etc) and close it before I run this code then it will be fine when I run it. That's weird!!! Could anyone explain to me why I have to open the csv file and make some changes(just click on save button or change a value to another) to ignore the problem and how to fix it?
Check that your encoding when you save the file is the same encoding with the one you use when you read the file. It may well be that you are saving, for example, in UTF8 and reading the file as it would be UTF16.
This fits what you describe (if opening and saving the file before reading it, then it works) as well as the ""ArrayIndexOutOfBoundsException: 1"" - showing that the "split" method did not find any separator (the comma) thus return a single string.
It would also help if using a debugger to check what is in your array just-to-be-added-to findMaxColumn after splitting. Easier to debug if you use a local variable to store the result of split before adding:
while((line = br.readLine())!= null)
{
String splitResult[]=temp.split(","); // easier to examine
findMaxColumn.add(splitResult);
}

How to read the additional lines in a text file

I have an assignment to create a "map" which is really an array that contains rooms. In the rooms there are artifacts that you can look at or examine and put into your inventory or "backpack". You are also able to save and restore your placement on the map, along with the artifact locations and your inventory. The save function saves it to a text file with the location, artifacts, and inventory. The problem that I am running into is trying to get the artifact data from the text file to restore on the program. I have no problem loading the location, but can not load any artifacts. While running the debugger it skips over the line. Here is the piece of code I am trying to work.
File fileRestore = new File("C:\\Users\\mike\\Desktop\\GCPU.txt");
try
{
FileReader reader = new FileReader(fileRestore);
BufferedReader buffer = new BufferedReader(reader);
String line = buffer.readLine();
while (line !=null)
{
String[] contents = line.split(",");
String key = contents[0];
if (key.equals("StartLocation"))
{
row = Integer.parseInt(contents[1]);
col = Integer.parseInt(contents[2]);
}
key = contents [1];
if (key.equals("Artifact"))
{
String name = contents [1];
row = Integer.parseInt(contents [2]);
col = Integer.parseInt(contents [3]);
if (name.equals("vending"))
map.rooms[row][col].contents = map.vending;
if (name.equals("beaker"))
map.rooms[row][col].contents = map.beaker;
if (name.equals("gameboy"))
map.rooms[row][col].contents = map.gameboy;
if (name.equals("paper"))
map.rooms[row][col].contents = map.paper;
if (name.equals("trees"))
map.rooms[row][col].contents = map.trees;
if (name.equals("desk"))
map.rooms[row][col].contents = map.desk;
if (name.equals("brewer"))
map.rooms[row][col].contents = map.brewer;
if (name.equals("statue"))
map.rooms[row][col].contents = map.statue;
}
Here is the text file that I am reading from:
StartLocation,0,2
Artifact,Eerie statue,2,0
Artifact,A small redwood sprout,3,0
Artifact,Gameboy Color,0,1
Artifact,Lapdesk,1,1
Artifact,A piece of paper,2,1
Artifact,Industrial coffee maker,1,3
So to reiterate my question, how am I able to read the Artifact line from the text along with the StartLocation line?
Thank you for taking the time to read this.
You are only reading once from the file. Replacing these two lines:
String line = buffer.readLine();
while (line !=null)
...
With something like so:
String line = "";
while((line = buffer.readLine()) != null)
...
Should allow you to read the next line each time the while loop iterates.
Alternatively, you could also have a line = buffer.readLine() just before your closing brace for the while loop. This approach is also valid, however, judging by the tutorials I went through, simply less popular.
String line = buffer.readLine();
should be inside the while loop. It is being executed only once.
Although make sure to modify initial value of line and the loop condition such that the loop starts .
Good luck.
String line = buffer.readLine(); will skip over the first line.
2.
if (key.equals("StartLocation"))
{ row = Integer.parseInt(contents[1]);
col = Integer.parseInt(contents[2]);
}
will fail because key = " StartLocation". there is a space in your
text file. use line=line.trim() to remove unnecessary characters.
3. Your program will read only 1 line.

How to get proper string array when parsing CSV?

Using jcsv I'm trying to parse a CSV to a specified type. When I parse it, it says length of the data param is 1. This is incorrect. I tried removing line breaks, but it still says 1. Am I just missing something in plain sight?
This is my input string csvString variable
"Symbol","Last","Chg(%)","Vol",
INTC,23.90,1.06,28419200,
GE,26.83,0.19,22707700,
PFE,31.88,-0.03,17036200,
MRK,49.83,0.50,11565500,
T,35.41,0.37,11471300,
This is the Parser
public class BuySignalParser implements CSVEntryParser<BuySignal> {
#Override
public BuySignal parseEntry(String... data) {
// console says "Length 1"
System.out.println("Length " + data.length);
if (data.length != 4) {
throw new IllegalArgumentException("data is not a valid BuySignal record");
}
String symbol = data[0];
double last = Double.parseDouble(data[1]);
double change = Double.parseDouble(data[2]);
double volume = Double.parseDouble(data[3]);
return new BuySignal(symbol, last, change, volume);
}
}
And this is where I use the parser (right from the example)
CSVReader<BuySignal> cReader = new CSVReaderBuilder<BuySignal>(new StringReader( csvString)).entryParser(new BuySignalParser()).build();
List<BuySignal> signals = cReader.readAll();
jcsv allows different delimiter characters. The default is semicolon. Use CSVStrategy.UK_DEFAULT to get to use commas.
Also, you have four commas, and that usually indicates five values. You might want to remove the delimiters off the end.
I don't know how to make jcsv ignore the first line
I typically use CSVHelper to parse CSV files, and while jcsv seems pretty good, here is how you would do it with CVSHelper:
Reader reader = new InputStreamReader(new FileInputStream("persons.csv"), "UTF-8");
//bring in the first line with the headers if you want them
List<String> firstRow = CSVHelper.parseLine(reader);
List<String> dataRow = CSVHelper.parseLine(reader);
while (dataRow!=null) {
...put your code here to construct your objects from the strings
dataRow = CSVHelper.parseLine(reader);
}
You shouldn't have commas at the end of lines. Generally there are cell delimiters (commas) and line delimiters (newlines). By placing commas at the end of the line it looks like the entire file is one long line.

read data from a file in java

I have a text file in the following format:
Details.txt
The file is a .txt file. I want to read course title from this file and print corresponding textbook and instructor information. But i am not sure about what process to follow ? storing the information in an array won't be efficient! How should i proceed ? NOTE: I can't change the info in the file, it should not be changed!! obviously the file will be read by the following code:
File newFile=new File("C:/details");
but how should i extract the data from this file according to the labels course title, textbook and instructor!?
First read the file correctly line by line, and search for your entered course title, lets consider "Java"
Now you hit your title and you know you need 3 consecutive lines from your file as all information related to that title are there.
if(str.startsWith(title)); { // for title = "Java"
line1 = 1st line // contains ISBN and First Name
line2 = 2nd line // Title and Last Name
line3 = 3rd line // Author and Department
line4 = 4th line // Email
break; // this will take you out of while loop
}
Now on those four lines do string operations and extract your data as you need and use it.
I am home so I can't give you exact code. But if you follow this it will solve your issue. Let me know if any problem you got while doing this.
Follow this to get some info on String operations
Use String Tokenizer and separate each string and then store them in a Linked List or Array List. Have Separate List for each title like course title, instructor etc. and then print them
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
you can use FileUtils.readFileToString(new File(""C:/details.txt");
Now you can extract the required data based on your wish
Use Scanner class
Scanner s=new Scanner(new File("C:/Details.txt"));
while(s.hasNext())
{
System.out.println(s.nextLine());
}
if you want in work by word then use String Tokenizer
see this article

Categories