This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Convert array of strings into a string in Java
(14 answers)
Closed last month.
I have a string input file and I put the strings into arrays. I only want to print the last element of each string array onto my console and onto a output array. When I run my code, I get the last element of each string array onto my console, but see this on my output file:
[Ljava.lang.String;#51d5f7fd
How can I print the actual string array to show up on output file and not its string representation? I'll show you my code so you get a better understanding of what I'm trying to do:
try {
br = new BufferedReader(new FileReader("C:\\rd\\bubble.txt"));
//first, create new file object
File file = new File("C:\\rd\\bubble_out.txt");
if(file.exists()) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
String line = "";
while((line = br.readLine()) != null) { //while the line is not equal to null
String[] arr = line.split("\\s+"); //split at whitespace
System.out.println(arr[arr.length - 1]);
pw.println(arr);
pw.close();
}
}
catch(IOException x)
{
System.out.println("File not found");
}
}
}
}
}
I've tried using Array.toString() method, but I'm not sure how to implement it into my code correctly. I'm currently trying to do that, but if there's an easier way to do this, please let me know.
Use Arrays.toString to get a readable String representation of the array.
Don't close the PrintWriter inside the loop as you have not finished writing all output. You can use try with resources to avoid having to explicitly close it.
try (PrintWriter pw = new PrintWriter(file)) {
while((line = br.readLine()) != null) {
String[] arr = line.split("\\s+");
System.out.println(arr[arr.length - 1]);
pw.println(Arrays.toString(arr));
}
}
Related
This question already has answers here:
BufferedReader is skipping every other line when reading my file in java
(3 answers)
Closed 3 years ago.
private static List<Book> readDataFromCSV(String fileName) {
List<Book> books = new ArrayList<>();
Path pathToFile = Paths.get(fileName);
// create an instance of BufferedReader
// using try with resource, Java 7 feature to close resources
try (BufferedReader br = Files.newBufferedReader(pathToFile,
StandardCharsets.US_ASCII)) {
// read the first line from the text file
String line = br.readLine();
// loop until all lines are read
while ((line = br.readLine())!= null) {
// use string.split to load a string array with the values from
// each line of
// the file, using a comma as the delimiter
String[] attributes = line.split("\\|");
Book book = createBook(attributes);
// adding book into ArrayList
books.add(book);
// read next line before looping
// if end of file reached, line would be null
line = br.readLine();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return books;
}
private static Book createBook(String[] metadata) {
String name = metadata[0];
String author = metadata[1]; // create and return book of this metadata
return new Book(name, price, author);
}
The above code skips every second line from text file (a csv file).
It gives data of alternate lines and it uses Java 7 syntax.
Please provide some suggestion what is wrong or how to improve it.
Remove the br.readLine() inside the while condition i.e.
// read the first line from the text file
String line = br.readLine();
// loop until all lines are read
while (line != null)
{
...
// read next line before looping
// if end of file reached, line would be null
line = br.readLine();
}
You have called the br.readLine() function twice in the loop.
One is in the condition:
while((line = br.readLine()) != null)
and the second one is at end of the loop.
So the loop is actually reading a line at the end, and then reading the next line at the beginning without processing it. To avoid this, you can remove the br.readLine at the end of the loop.
while ((line = br.readLine())!= null)
{
// use string.split to load a string array with the values from
// each line of
// the file, using a comma as the delimiter
String[] attributes = line.split("\\|");
Book book = createBook(attributes);
// adding book into ArrayList
books.add(book);
}
If you did not get it, the condition:
while((line = br.readLine()) != null)
is actually doing the following:
storing the returned value of br.readLine() in the variable line,
and then checking the condition. Therefore, you do not need to call it again in the loop.
This question already has answers here:
How can I read comma separated values from a text file in Java?
(6 answers)
How do I split a string in Java?
(39 answers)
Closed 3 years ago.
I want to load data from a text file as required for part of a basic project. E.g. a text file can look like this:
201,double,70.00,2,own bathroom
202,single,50.00,2,own bathroom
Each piece of data is seperated by a comma, and in this case goes in the order: room number, room type, cost, amount of people, with/without bathroom and there's 5 data for each room and each room information is on a new line.
The code below reads each line individually, but how do I get it to read and store each data/word from the line (without the comma obviously)?
try{
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = reader.readLine();
while (line != null){
System.out.println(line);
line = reader.readLine();
}
reader.close();
} catch(IOException ex){
System.out.println(ex.getMessage());
}
I saw an example using scanner but I heard that it's slower and less efficient.
I also tried using split but I can't figure out how to do it properly.
Thanks.
You can use Files.readAllLines() method and map the data to the dedicated object. Assuming you have such Room object with appropriate constructor you can read and store data like:
List<String> strings = Files.readAllLines(Paths.get("test.txt"));
List<Room> rooms = new ArrayList<>();
for (String line : strings) {
String[] split = line.split(",");
Integer roomNumber = Integer.valueOf(split[0]);
String roomType = split[1];
Double roomCost = Double.valueOf(split[2]);
Integer amount = Integer.valueOf(split[3]);
String bathroom = split[4];
Room r = new Room(roomNumber, roomType, roomCost, amount, bathroom);
rooms.add(r);
}
Then you can get the information for some room for example by room number:
Room room = rooms.stream()
.filter(r -> r.getRoomNumber() == 102)
.findFirst().orElseThrow(NoSuchElementException::new);
Note: If you are using java10 or above you can use orElseThrow() without parameters
You can split the line by the comma , and get an array of values:
try{
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = reader.readLine();
String data[] = null;
while (line != null){
System.out.println(line);
line = reader.readLine();
data = line.split(","); //data will have the values as an array
}
reader.close();
} catch(IOException ex){
System.out.println(ex.getMessage());
}
If I´m not wrong then the described format is the csv format ( https://en.wikipedia.org/wiki/Comma-separated_values)
Here is good overview how you can read csv data:
https://www.baeldung.com/java-csv-file-array
My code works fine however it prints the values side by side instead of under each other line by line. Like this:
iatadult,DDD,
iatfirst,AAA,BBB,CCC
I have done a diligent search on stackoverflow and none of my solution's seem to work. I know that I have to make the change while the looping is going on. However none of the examples I have seen have worked. Any further understanding or techniques to achieve my goal would be helpful. Whatever I am missing is probably very small. Please help.
String folderPath1 = "C:\\PayrollSync\\client\\client_orginal.txt";
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array
try {
BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
String line;
while (( line = reader.readLine()) != null) {
if(line.contains("fooa")||line.contains("foob")){
fileContents.add(line);
}
//---------------------------------------
}
reader.close();// close reader
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents);
Add a Line Feed before you add to fileContents.
fileContents.add(line+"\n");
By printing the list directly as you are doing you are invoking the method toString() overridden for the list which prints the contents like this:
obj1.toString(),obj2.toString() .. , objN.toString()
in your case the obj* are of type String and the toString() override for it returns the string itself. That's why you are seeing all the strings separated by comma.
To do something different, i.e: printing each object in a separate line you should implement it yourself, and you can simply append the new line character('\n') after each string.
Possible solution in java 8:
String result = fileContents.stream().collect(Collectors.joining('\n'));
System.out.println(result);
A platform-independent way to add a new line:
fileContents.add(line + System.lineSeparator);
Below is my full answer. Thanks for your help stackoverflow. It took me all day but I have a full solution.
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array
try {
BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
String line;
while (( line = reader.readLine()) != null) {
String [] names ={"iatdaily","iatrapala","iatfirst","wpolkrate","iatjohnson","iatvaleant"};
if (Stream.of(names).anyMatch(line.trim()::contains)) {
System.out.println(line);
fileContents.add(line + "\n");
}
}
System.out.println("---------------");
reader.close();// close reader
} catch (Exception e) {
System.out.println(e.getMessage());
}
This question already has answers here:
Advanced PDF parser for Java
(5 answers)
Closed 7 years ago.
I would like to ask, how can i parse text. I had extracted text from PDF file with PDFBox into normal text, which is output in console. For example this one:
SHA256: 51c11994540537b633cf91b276b3c34556695ed870a5d3f7451e993262a4a745
File name: ACleaner.zip
Detection ratio: 0 / 55
Analysis date: 20150721 12:23:19 UTC ( 8 minutes ago )
0 0
? Analysis ? File detail ? Additional information ? Comments 0 ? Votes
MD5 fffa183f43766ed39d411cb5f48dbc87
SHA1 b0d40fbc6c722d59031bb488455f89ba086eacd9
SHA256 51c11994540537b633cf91b276b3c34556695ed870a5d3f7451e993262a4a745
I need to get some values, for example value of MD5, File name etc..how can i reach it in Java? Thanks a lot
I have tried so : in this while a i added this
String keySHA256 = "SHA256:";
private static String SHA256Value = null;
if (line.contains(keySHA256)) {
// System.out.println(line);
int length = keySHA256.length();
SHA256Value = line.substring(length);
System.out.println("SHA256 >>>>" + SHA256Value);
}
but sometimes it doesnt get right value..please help..
This could be a good example for you to start learning more about Java IO and String parsing. Google is your friend.
//uri where your file is
String fileName = "c://lines.txt";
// read the file into a buffered reader
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) { //iterate on each line of the file
System.out.println(line); // print it if you want
String[] split=line.split(" "); // split your line into array of strings, each one is a separate word that has no spaces in it.
//add any checks or extra processes here
}
} catch (IOException e) {
e.printStackTrace();
}
This problem takes a bit of explaining, I'll try to be as concise as possible:
I have am trying to initalise an array of Can objects, these objects only have 2 fields (both Strings): name, manufacturer
I am trying to initialise the fields by reading from a CSV file with the following format:
Tomatoes,Heinz
Legumes,Jerry
(no space between the lines, it's being formatted like that on this site for some reason)
The first string in each row is the value I want to be the name, the 2nd is the manufacturer.
So I've created a method to read each line of the CSV, which passes each line to a tokenizer method to extract single values:
private void readFile (String inFilename) {
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
int lineNum;
String line;
try {
fileStrm = new FileInputStream(inFilename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
lineNum = 0;
line = bufRdr.readLine();
while {line != null) {
lineNum++;
processLine(line); //passes line to tokenizer
line = bufRdr.readLine();
}
fileStrm.close();
}
catch (IOException e) {
if (fileStrm != null) {
try { fileStrm.close(); } catch (IOException ex2) { }
}
System.out.println("Error in file processing: " + e.getMessage());
}
}
The lines are passed to this tokenizer method:
private String processLine(String csvRow) {
String thisToken = null;
StringTokenizer strTok;
strTok = new StringTokenizer(csvRow, ",");
while (strTok.hasMoreTokens()) {
thisToken = strTok.nextToken();
}
}
And that's where I get a bit stuck. To initialise my array I think I'd need a for loop, something like
for (int i=0; i<=array.length;i++)
{
array[i].name = readFile("filename.csv");
array[i].manufacturer = readFile("filename.csv");
}
But obviously this will not work. Can anyone suggest how I can go about this? I'd prefer to keep the code mostly intact and figure out a solution using the existing code.
Thanks
First thing: -
You are calling processLine(line);, but are not returning the token read from this method.. So, the token obtained in this method in engulped there only.. So, you should return something from that method..
Second:-
array[i].name = readFile("filename.csv");
array[i].manufacturer = readFile("filename.csv");
In the above code, you are calling readFile() each time for the two attributes.. So, even if you return somthing, these two attributes will be initialized to same value.. Because each time you are starting reading file from scratch..
Third thing: -
In fact your above code will not compile.. Because you are assigning the value of readFile() (which is actually not returning anything) to array.. So give a return type to this method.. It would be String.. And returning the tokens read..
EDIT: -
* I would suggest, you can use split() method of String class.. Tokenizer is not needed here, for justsplittingaround a singlecomma(,)`
Also, rather than using an array, you can use ArrayList, in which you can add your newly created object on the fly.. That way, you will not have to fix the size of array.. (And this is what you will want, as you don't know how much line you will have in your file right?)
Here's what you can do: -
Call the method readFile from somewhere, probably main()
readFile("filename.csv")
In your readFile() method, you can iterate over file to create an ArrayList like this: -
List<Can> yourList = new ArrayList<>();
while ((line = reader.readLine()) != null) {
String[] wordRead = line.split(',');
yourList.add(new Can(wordRead[0], wordRead[1]));
}
I assume, Can is the name of your class as you stated in your problem..