How to parse text file - java

demo.txt :
FD1,true,102400,4000,0.01,103,83.25
FD0,false,102400,4000,0.01,103,83.25
I want to access each line 1st then from each line i want to access each element and pass this as parameter to a function createFogDevice to perform some action.
like createFogDevice(FD1,true,1024,4000,0.01,103,83.25)
Can anybody help how we can write code for this ?

Scanner scanner = new Scanner(new File());
while(scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
String[] dataPoints = currentLine.split(",");
String a = dataPoints[0];
boolean b = Boolean.parseBoolean(dataPoints[1]);
// ....
createFogDevice(a,b,c/*...*/);
}

Try This :-
try (Stream<String> stream = Files.lines(Paths.get("demo.txt"))) {
stream.forEach(ob->createFogDevice(ob.split(",")));
} catch (IOException e) {
e.printStackTrace();
}
Also you can modify createFogDevice() method to pass Array of String as argument :-
private static void createFogDevice(String[] inputParams) {
// your code goes here
}

Related

How to return inside a while loop?

I want to have a method that returns the value that is presentend in the while loop. My code represents the reading of a txt file, where I read line by line and my goal is to return everytime it founds a line but is is showing me the same number over and over.
public String getInputsTxtFromConsole() {
String line = "";
//read inputs file
try {
Scanner scanner = new Scanner(inputFile);
//read the file line by line
int lineNum = 0;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
lineNum++;
//Return statement does not work here
}
} catch (FileNotFoundException e) {
}
return "";
}
As Nick A has said the use of return has, in this context two uses: return the value of a function and exit the function. I you need all the values as the are generated you can, for example,
Call a method that consume the new value:
line = scanner.nextLine();
lineNum++;
//Return statement does not work here
ConsumerMethod(line);
}
Store in a global var like ArrayList, String[],...
Print it System.out.println(line).
...
But you cannot return a value and expect that the function continues working.
As I mentioned, pass the same scanner as a parameter to a method that reads a line and returns the line. You may want to define how it responds once there are no remaining lines.
public String getInputsTxtFromConsole(Scanner scanner) {
try {
if (scanner.hasNextLine()) {
return scanner.nextLine();
}
} catch (FileNotFoundException e) {
}
return null;
}
I would also recommend using a different class to read from a file. BufferedReader would be a better approach.
BufferedReader in = new BufferedReader(new FileReader (file));
... // in your method
return in.readLine(); //return null if the end of the stream has been reached

List<String> with entities to encode to UTF-8

I have list which get regex value and add to List
private static List<String> listaOfQuestion(Scanner sc, List<File> listaQuestion) {
List<String> question = new ArrayList<String>();
for (File input1 : listaQuestion) {
try {
sc = new Scanner(input1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc.hasNextLine()) {
Scanner s = new Scanner(sc.nextLine());
while (s.hasNext()) {
String words = s.nextLine();
try {
question.add(getTagValuesQ(words).toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return question;
}
I want to parse all value like
List
Bielańska
Wyziński
Wciślik
To
List
Bielańska
Wyzińska
Wciślik
To UTF-8, i'm searching throught the forum, and i didn't see solution or i just dont get it.
I appreciate every form of help, but because i'm new the best will be standard example or something like this which i will be able to understand.
I solved my problem, i needed use
<...>
Scanner s = new Scanner(sc.nextLine());
while(s.hasNext()){
String words = s.nextLine();
String decoded = org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(words);
<...>
I tried using Apache Common Lang and solved it:
String s = "Bielańska Wyziński Wciślik";
String decoded = org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(s);
System.out.println(decoded);
Output:
Bielańska Wyziński Wciślik
https://commons.apache.org/proper/commons-lang/download_lang.cgi

Save String with random number of lines to single line array JAVA

So here is the method which is reading from the file, it then splits the information by the # sign. which is where a new month begins in the text file
public static String readPurchaseOrder(Scanner sc) {
final String DELIMITER = "#";
try {
while (sc.hasNext()) {
sc.useDelimiter(DELIMITER);
String data = sc.next();
return data;
}
} catch (Exception e) {
System.out.println(e);
}
sc.close();
return null;
}
The text file contains information shown below up to the 12th month
04/01/12#PNW-1234#PA/1234#10
15/01/12#BSE-5566#bT/4674#5#
08/02/12#PNE-3456#Xk/8536#1#
07/03/12#PEA-4567#ZR/7413#3
09/03/12#ESE-6329#HY/7195#30#
03/04/12#ESE-5577#LR/4992#12
23/04/12#PNW-1235#HY/7195#2#
09/05/12#ESE-6329#PV/5732#6
25/05/12#BSE-5566#PV/5732#10#
08/06/12#PNE-3457#kD/9767#1
31/06/12#EMI-6329#ZR/7413#10#
03/07/12#EMI-6329#PV/5732#12
25/07/12#BSE-5566#bT/4674#5#
I am using this to output the information from the file split by the #
for (int i = 0; i <12; i ++){
String str[] = InputFileData.readPurchaseOrder(sC).split("\\n");
for(String s : str){
System.out.println(s);
}
It outputs the data like this
04/01/12#PNW-1234#PA/1234#10
15/01/12#BSE-5566#bT/4674#5
08/02/12#PNE-3456#Xk/8536#1
07/03/12#PEA-4567#ZR/7413#3
09/03/12#ESE-6329#HY/7195#30
03/04/12#ESE-5577#LR/4992#12
23/04/12#PNW-1235#HY/7195#2
09/05/12#ESE-6329#PV/5732#6
25/05/12#BSE-5566#PV/5732#10
I want to store each individual line in an array, so I can then further split up the line to its each respective variables
If you would like to collect the results in an array, one line per array element, the easiest way to do it is to use a list (since you don't know in advance the number of lines), and then convert it to an array. The size of an array has to be declared in advance, so you want to use a more flexible data structure if you don't know how big it's going to be.
public static String[] readPurchaseOrder(Scanner sc) {
final String DELIMITER = "#";
List<String> results = new ArrayList<>();
try {
while (sc.hasNext()) {
sc.useDelimiter(DELIMITER);
String data = sc.next();
results.add(data); // add the line to the list
}
} catch (Exception e) {
System.out.println(e);
}
sc.close();
// convert the list to an array and return it.
return results.toArray(new String[results.size()]);
}

remove '#' symbol from the beginning of the string in java

Sample data in csv file
##Troubleshooting DHCP Configuration
#Module 3: Point-to-Point Protocol (PPP)
##Configuring HDLC Encapsulation
Hardware is HD64570
So i want to get the lines as
#Troubleshooting DHCP Configuratin
Module 3: Point-to-Point Protocol(PPP)
#Configuring HDLC Encapsulation
Hardware is HD64570
I have written sample code
public class ReadCSV {
public static BufferedReader br = null;
public static void main(String[] args) {
ReadCSV obj = new ReadCSV();
obj.run();
}
public void run() {
String sCurrentLine;
try {
br = new BufferedReader(new FileReader("D:\\compare\\Genre_Subgenre.csv"));
try {
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.charAt(0) == '#'){
System.out.println(sCurrentLine);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am getting below error
##Troubleshooting DHCP Configuration
#Module 3: Point-to-Point Protocol (PPP)
##Configuring HDLC Encapsulation
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at example.ReadCSV.main(ReadCSV.java:19)
Please suggest me how to do this?
Steps:
Read the CSV file line by line
Use line.replaceFirst("#", "") to remove the first # from each line
Write the modified lines to an output stream (file or String) which suites you
If the variable s contains the content of the CSV file as String
s = s.replace("##", "#");
will replace all the occurrencies of '##" with '#'
You need something like String line=buffer.readLine()
Check the first character of the line with line.charAt(0)=='#'
Get the new String with String newLine=line.substring(1)
This is a rather trivial question. Rather than do the work for you, I'll outline the steps that you need to take without gifting you the answer.
Read in a file line by line
Take the first line and check if the first character of this line is a # - If it is, create a substring of this line excluding the first character ( or use fileLine.replaceFirst("#", ""); )
Store this line somewhere in an array like data structure or simply replace the current variable with the edited one ( fileLine = fileLine.replaceFirst("#", ""); )
Repeat until no more lines left from file.
If you want to add these changes to the file, simply overwrite the old file with the new lines (e.g. Using a steam reader and setting second parameter to false would overwrite)
Make an attempt and show us what you have tried, people will be more likely to help if they believe you have attempted the problem yourself thoroughly first.
package stackoverflow.q_25054783;
import java.util.Arrays;
public class RemoveHash {
public static void main(String[] args) {
String [] strArray = new String [3];
strArray[0] = "##Troubleshooting DHCP Configuration";
strArray[1] = "#Module 3: Point-to-Point Protocol (PPP)";
strArray[2] = "##Configuring HDLC Encapsulation";
System.out.println("Original array: " + Arrays.toString(strArray));
for (int i = 0; i < strArray.length; i++) {
strArray[i] = strArray[i].replaceFirst("#", "");
}
System.out.println("Updated array: " + Arrays.toString(strArray));
}
}
//Output:
//Original array: [##Troubleshooting DHCP Configuration, #Module 3: Point-to-Point Protocol (PPP), ##Configuring HDLC Encapsulation]
//Updated array: [#Troubleshooting DHCP Configuration, Module 3: Point-to-Point Protocol (PPP), #Configuring HDLC Encapsulation]
OpenCSV reads CSV file line by line and gives you an array of strings, where each string is one comma separated value, right? Thus, you are operating on a string.
You want to remove '#' symbol from the beginning of the string (if it is there). Correct?
Then this should do it:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
if (nextLine[0].charAt(0) == '#') {
nextLine[0] = nextLine[0].substring(1, nextLine[0].length());
}
}
Replacing the first '#' symbol on each of the lines in the CSV file.
private List<String> getFileContentWithoutFirstChar(File f){
try (BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(f), Charset.forName("UTF-8")))){
List<String> lines = new ArrayList<String>();
for(String line = input.readLine(); line != null; line = input.readLine()) {
lines.add(line.substring(1));
}
return lines
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
return null;
}
}
private void writeFile(List<String> lines, File f){
try(BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8))){
for(String line : lines){
bw.write(content);
}
bw.flush();
}catch (Exception e) {
e.printStackTrace();
}
}
main(){
File f = new File("file/path");
List<Stirng> lines = getFileContent(f);
f.delete();
writeFile(lines, f);
}

ArrayList confusion

The code below is my attempt to read from a file of strings, read through each line until a ':' is found then store + print everything after that. however The print function prints out everything that I read in from the file. Can someone spot where I'm going wrong? thanks
edit: every line is in this format "Some text here:More text here"
public void openFile() {
try {
scanner = new BufferedReader(new FileReader("calendar.ics"));
} catch (Exception e) {
System.out.println("Could not open file");
}
}
public void readFile() {
ArrayList<String> vals = new ArrayList<String>();
String test;
try {
while ((line = scanner.readLine()) != null)
{
int indexOfComma = line.indexOf("\\:"); // returns firstIndexOf ':'
test = line.substring(indexOfComma+1); // test to be everything after ':'
vals.add(test); // add values to vals
}
} catch(Exception ex){ }
for(int i=0; i<vals.size(); i++){
System.out.println(vals.get(i));
}
}
You don't need to escape your colon.
line.indexOf("\\:");
Change the above line to: -
line.indexOf(":");
Because, that will search for \\:, and if not found return the value -1.
test = line.substring(indexOfComma+1);
So, if your indexComma is -1, which will certainly be, if your string does not contain - \\:, then your above line becomes: -
line.substring(0); // same as whole string
As a suggestion, you should have abstract type as the type of reference when declaring your list. So, you should use List instead of ArrayList on the LHS of the List declaration: -
List<String> vals = new ArrayList<String>();

Categories

Resources