I would need to parse a text file with below format and extract only the required values from the text file. the content of the text file is
4564444 FALSE / TRUE 0 name k0LiuME5Q3
4342222 TRUE / TRUE 0 id ab4454jj
i need to get the values after name and id. what is the best way. I used Scanner Class in java but could not get the values. tried with below code.
Scanner scanner = new Scanner(new File("test.txt"));
while(scanner.hasNext()){
String[] tokens = scanner.nextLine().split(" ");
String last = tokens[tokens.length - 1];
System.out.println(last);
}
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Read_Text_File {
public static void main(String[] args) {
System.out.println(getValues());
}
public static ArrayList<String> getValues() {
FileInputStream stream = null;
try {
stream = new FileInputStream("src/resources/java_txt_file.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String strLine;
ArrayList<String> lines = new ArrayList<String>();
try {
while ((strLine = reader.readLine()) != null) {
String lastWord = strLine.substring(strLine.lastIndexOf(" ")+1);
lines.add(lastWord);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
}
Output:
[k0LiuME5Q3, ab4454jj]
You need to split by space, not semicolon:
String[] tokens = scanner.nextLine().split(" ");
read the data line by line, on each line use String.split("\s*") to get the parts without the whitespace into an array with 7 elements. the last one of these elements is what you are looking for.
Related
For a project of mine, I'm trying to read a file of Integers and save each line into a file. Each of the files I'm reading have a different amount of lines.
The file would look like
17
72
61
11
63
95
100
Is there a way I can use a loop and save the value in a different variable for each line?
Create a Collection to capture your values. We can use a List so we maintain the input order.
List<Integer> list = new ArrayList<>();
Create a mechanism for reading from the file. A common option is a Scanner. The Scanner is Autoclosable so we'll put it in a try-with-resources block so we don't have to close it ourselves.
try (Scanner scanner = new Scanner(new File(fileName))) {
... do stuff ...
}
While the Scanner has values, read a value and add it to the List.
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
In sum...
List<Integer> list = new ArrayList<>();
try (Scanner scanner = new Scanner(yourFileName)) {
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
}
Assuming you just want to take a line and copy it into another file, here you go: Reading the file as long as there are lines and just change System.out.println(line); (line 16) to create and write to the file (and there just add an incrementing index (like index++ executed at the end of "while") to the filename and pass "line" to the write function).
The only thing that is important: close the BufferedReader and the FileWriter!!
Something like this:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReadFileLineByLineUsingBufferedReader {
public static void main(String[] args) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = reader.readLine();
int index = 0;
while (line != null) {
createFile(index);
writeToFile(line, index);
index++;
// read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void CreateFile (int index) {
try {
File myObj = new File("filename" + index + ".txt");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public void WriteToFile (String content, int index) {
try {
FileWriter myWriter = new FileWriter("filename" + index + ".txt");
myWriter.write(content);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
So what my code does is, checks whether the file has certain number of columns. if the columns are less than the specified amount of columns it adds the string "null" from the next line.
Furthermore, the code copies the content in file "text" using org.apache.io and puts it into new file named "test".
(content in file "text is in two rows").
I want the content to be shown in file "test" in a single line.
package MySQL;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import org.apache.commons.io.*;
public class Add {
public static void main(String args[]) throws IOException {
File file = new File("C:\\Users\\dhruv\\Desktop\\Practicals\\IntelliJ\\src\\MySQL\\text.txt");
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int number = 0;
if (scanner.hasNextLine()) {
number = scanner.nextLine().split(" ").length;
}
System.out.println(number);
scanner.close();
if (number < 10) {
FileWriter bw_1 = new FileWriter("C:\\Users\\dhruv\\Desktop\\Practicals\\IntelliJ\\src\\MySQL\\text.txt", true);
BufferedWriter bw = new BufferedWriter(bw_1);
PrintWriter out = new PrintWriter(bw);
for (int i = 0; i < 10-number; i++)
{
out.write("Null");
out.write(" ");
}
out.close();
}
File file_1 = new File("C:\\Users\\dhruv\\Desktop\\Practicals\\IntelliJ\\src\\MySQL\\text.txt");
String content = null;
try {
content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(content);
Path path = Paths.get("C:\\Users\\dhruv\\Desktop\\Practicals\\IntelliJ\\src\\MySQL\\test.txt");
//String contents = ;
try {
Files.writeString(path, content, StandardCharsets.UTF_8);
} catch (IOException ex) {
}
}
}
"text" file
I am trying to read a file from my computer, and have the system print out the file only containing the letters, and not printing the numbers. I have other functions in my code already so please look near the bottom where I am stuck with arraylist. How do I ignore the integers when printing?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader reader = null;
ArrayList <String> myFileLines = new ArrayList <String>();
try {
String sCurrentLine;
reader = new BufferedReader(new FileReader("/Users/wolftrek/Downloads/example.txt"));
while ((sCurrentLine = reader.readLine()) != null) {
myFileLines.add(sCurrentLine);
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
for (int i = 0; i < myFileLines.size(); i++) {
if (myFileLines.get(i).contains("example word")) {
System.out.println(myFileLines.get(i));
}
}
Scanner myScanner = new Scanner (System.in);
String enteredString = "";
System.out.println("Please enter the characters to search for: ");
enteredString = myScanner.nextLine();
for(int i = 0; i < myFileLines.size(); i++) {
if (myFileLines.get(i).contains(enteredString)) {
System.out.println(myFileLines.get(i));
}
}
ArrayList<String> input = myFileLines;
String extract = input.replaceAll("[^a-zA-Z]+", "");
System.out.println(extract);
}
}
The error is you are applying replaceAll on a list and also the regex is not correct. Something like below will do the job. I am not clear if that's what you want though.
ArrayList<String> input = myFileLines;
for (String e : input) {
String extract = e.replaceAll("\\d+", "");
System.out.println(extract);
}
I am getting a null value when im reading from my teachers. csv file. Column 1 which is att[0] works but att[1] returns 3 null values.
My csv looks like this:
1, Mr Murphy
2, Mr Davis
3, Ms Simpson
Each on separate lines ie line 1 -> 1, Mr Murphy etc
Here is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadCSV
{
public static void main(String[] args)
{
//Input file which needs to be parsed
String readTeachers = "teacher.csv";
BufferedReader fileReader = null;
//Delimiter used in CSV file
final String DELIMITER = ",";
try
{
String line = "";
//String line = inFile.readLine();
//Create the file reader
fileReader = new BufferedReader(new FileReader(readTeachers));
int count=0;
String[] att = new String[10];
//Read the file line by line
while ((line = fileReader.readLine()) != null)
{
//Get all tokens available in line
String[] tokens = line.split(DELIMITER);
int i=0;
count++;
for(String token : tokens)
{
att[i] = token;
i++;
//Print all tokens
// System.out.println(token);
System.out.println(att[1]);
break;
}
}
//System.out.println(count);
//System.out.println(att[1]);
}
catch (Exception e) {
e.printStackTrace();
}
finally
{
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Your issue here is that you have a break statement inside the for loop that exits the loop at the end of the first iteration. Therefore, you are only putting a value in the first index of your array. Take out that statement and it should be fine.
for(String token : tokens)
{
att[i] = token;
i++;
//Print all tokens
// System.out.println(token);
System.out.println(att[1]);
break; // <---- ***take this out***
}
I'm looking to sort the contacts read from a file in alphabetical order by last name to the console? How would I go about doing so? The contacts are already written to file starting with the last name, I just want to read them back into the application in alphabetical order when a user wants to view the contacts in the console.
// Read from file, print to console. by XXXXX
// ----------------------------------------------------------
int counter = 0;
String line = null;
// Location of file to read
File file = new File("contactlist.csv");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
counter++;
}
scanner.close();
} catch (FileNotFoundException e) {
}
System.out.println("\n" + counter + " contacts in records.");
}
break;
// ----------------------------------------------------------
// End read file to console. by XXXX
Before printing, add each line to a sorted set, as a TreeSet:
Set<String> lines = new TreeSet<>();
while (scanner.hasNextLine()) {
line = scanner.nextLine();
lines.add(line);
counter++;
}
for (String fileLine : lines) {
System.out.println(fileLine);
}
package main.java.com.example;
import java.io.*;
import java.net.URL;
import java.util.Set;
import java.util.TreeSet;
public class ReadFromCSV {
public static void main(String[] args) {
try {
final ClassLoader loader = ReadFromCSV.class.getClassLoader();
URL url = loader.getResource("csv/contacts.csv");
if (null != url) {
File f = new File(url.getPath());
BufferedReader br = new BufferedReader(new FileReader(f));
Set<String> set = new TreeSet<String>();
String str;
while ((str = br.readLine()) != null) {
set.add(str);
}
for (String key : set) {
System.out.println(key);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Read names from the file, put them in an object of class SortedSet.