How to read a file, Split the contents and print it? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i have a file named "file" which is a text file(the file contains 1,2,3,4 integers).. Now i want to read this file and split the values in the file and print each value in new line. How can i do that??

Try this:
public static void main( String args[] )
{
try {
Scanner sc = new Scanner(new File("number.txt"));
sc.useDelimiter(",");
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

public class Main {
public static void main(String[] str) throws Exception{
File f = new File("C:\\prince\\temp\\test.txt");
FileInputStream fis = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
String[] splitedTokens = line.split("[,]");
for (String splitedToke : splitedTokens) {
System.out.println(splitedToke);
}
}
}
}

Related

how to read the number of columns in text file in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
how to read the number of columns in text file in java.
Example text file as below. Comma separated. In this i need to get the total column as count 4
ABC,BBC,12-10-2018,1234
ABC,BBC,12-10-2018,1234
ABC,BBC,12-10-2018,1234
ABC,BBC,12-10-2018,1234
The simplest way is to use a Scanner and read the 1st line.
By using split() with , as a delimeter you get an array and its length is what you want.
public static int getFileColumnsNumber(String filename) {
File file = new File(filename);
Scanner scanner;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return -1;
}
int number = 0;
if (scanner.hasNextLine()) {
number = scanner.nextLine().split(",").length;
}
scanner.close();
return number;
}
public static void main(String[] args) {
String filename = "test.txt";
System.out.println(getFileColumnsNumber(filename));
}

How Can I Read the Movie Names Only? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a data like this
1|Toy Story (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Toy%20Story%20(1995)|0|0|0|1|1|1|0|0|0|0|0|0|0|0|0|0|0|0|0
2|GoldenEye (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?GoldenEye%20(1995)|0|1|1|0|0|0|0|0|0|0|0|0|0|0|0|0|1|0|0
3|Four Rooms (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Four%20Rooms%20(1995)|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|1|0|0
4|Get Shorty (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Get%20Shorty%20(1995)|0|1|0|0|0|1|0|0|1|0|0|0|0|0|0|0|0|0|0
5|Copycat (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Copycat%20(1995)|0|0|0|0|0|0|1|0|1|0|0|0|0|0|0|0|1|0|0
and suppose the link part is in the same line with the movie names part.I am
only interested in movie numbers in the leftmost part and the movie names.
How can I read this file in Java and return like:
1|Toy Story
2|GoldenEye
Thanks for helping in advance.
Pretty easy, just split on " (" and remember to escape it using \\.
public static void main(String[] args) {
String result = movie("1|Toy Story (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Toy%20Story%20(1995)|0|0|0|1|1|1|0|0|0|0|0|0|0|0|0|0|0|0|0");
System.out.println(result); //prints 1|Toy Story
}
public static String movie(String movieString){
return movieString.split(" \\(")[0];
}
You can use regular expressions to extract the part that you want.
It is assumed that a movie title only contains word characters or spaces.
List<String> movieInfos = Arrays.asList(
"1|Toy Story (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Toy%20Story%20(1995)|0|0|0|1|1|1|0|0|0|0|0|0|0|0|0|0|0|0|0",
"2|GoldenEye (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?GoldenEye%20(1995)|0|1|1|0|0|0|0|0|0|0|0|0|0|0|0|0|1|0|0",
"3|Four Rooms (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Four%20Rooms%20(1995)|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|1|0|0",
"4|Get Shorty (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Get%20Shorty%20(1995)|0|1|0|0|0|1|0|0|1|0|0|0|0|0|0|0|0|0|0",
"5|Copycat (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Copycat%20(1995)|0|0|0|0|0|0|1|0|1|0|0|0|0|0|0|0|1|0|0"
);
Pattern pattern = Pattern.compile("^(\\d+)\\|([\\w\\s]+) \\(\\d{4}\\).*$");
for (String movieInfo : movieInfos) {
Matcher matcher = pattern.matcher(movieInfo);
if (matcher.matches()) {
String id = matcher.group(1);
String title = matcher.group(2);
System.out.println(String.format("%s|%s", id, title));
} else {
System.out.println("Unexpected data");
}
}
This works only if you have all the lines formated like that.
private static final String FILENAME = "pathToFile";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
ArrayList<String> output = new ArrayList<>();
try {
//br = new BufferedReader(new FileReader(FILENAME));
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String currentLine;
while ((currentLine= br.readLine()) != null) {
String movie = currentLine.split(" \\(")[0];
output.add(movie);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Considering the file format is the same as you have given, read the file line by line and for each read line, split it on the "(" parenthesis and print the first index in the resultant array obtained after the split operation.
static void readMovieNamesFromFile(String fileName) {
try (BufferedReader br = new BufferedReader(new FileReader(new File(fileName)))) {
String line;
while( (line = br.readLine()) != null){
System.out.println((line.split("\\(")[0]).trim());
}
} catch (IOException e) {
e.printStackTrace();
}
}
Assuming you are reading t.txt
File file = new File("t.txt");
try {
Scanner in = new Scanner(file);
while(in.hasNextLine())
{
String arr[] = in.nextLine().split("\\|");
if(arr.length > 1)
{
System.out.println(arr[0] +"|"+arr[1].split("\\(")[0]);
System.out.println();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Will give you as an output
1|Toy Story
2|GoldenEye
3|Four Rooms
4|Get Shorty
5|Copycat
There are 2 things which you have to take care in this.
(Here we assume we are reading the first line)
Split by |. Now since | is a meta character you have to use to escape it. Hence in.nextLine().split("\\|");
Now arr[0] will contain 1 and arr[2] will contain Toy Story (1995). So we split arr[2] via "(". you need the first match hence you can write it as arr[1].split("\\(")[0]) (you again have to escape it as "(" is also a metacharacter).
PS : if(arr.length > 1) this line is there to avoid blank new lines so that you don't end up with ArrayIndexOutOfBoundsException.
You can save data in String
For example
String name = //data of move
Then use if with is char
for(int i =0;i<name.lenght;i++)
{
if(name.charat(i).equals("(") //will read when it catch ( after name it will stop
{Break;}
Else
System.out.print("name.charat(i);
}
You can also fixt by other way

Android Studio Text to Speech.Need to browse File manager and then select .txt file to speech [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I know how to do TTS but need help in browsing file explorer and selecting a .txt file from anywhere in the sdcard and then push the text to textview. Below is my code.I can til now give specific file path and can only read from it. but need to make a file explorer to select .txt file.
package com.example.shubham.tts;
/**
* Created by shubham on 27/9/16.
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileOperations
{
public FileOperations()
{
}
public String read(String fname)
{
BufferedReader br = null;
String response = null;
try
{
StringBuffer output = new StringBuffer();
String fpath = "/sdcard/documents/"+fname;
br = new BufferedReader(new FileReader(fpath));
String line = "";
while ((line = br.readLine()) != null)
{
output.append(line +"\n");
}
response = output.toString();
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
return response;
}
}
Firstly you need to extract txt from your file ,if your file is on sd card
File exStrg= Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(exStrg,"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');
}
br.close();
}
catch (IOException e) {
//error handling here
}
Now get all string from .txt file and put it in
ttsInstance.speak(yourtext, TextToSpeech.QUEUE_FLUSH, null);
Let me know if it helped

java how to catch an exception in main? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I need to read lines from an input path (file).
to do so the main calls a class that uses BufferedReader , it iterates over each line and adds it to an Array.
the problem is:
I want to catch all exceptions thrown from the method in the class in the main.
public static void main (String[] args){
if (args.length != 2){
System.err.print("ERROR");
return;
}
MyFileScript.sourceDir = args[SOURCE_DIR_INDEX];
MyFileScript.commandFile = args[COMMAND_INDEX];
try (FileReader file = new FileReader(MyFileScript.commandFile);
BufferedReader reader = new BufferedReader(file)){
fileParsing = new CommandFileParser(reader);
sectionList = fileParsing.parseFile();
}catch (FileNotFoundException error){
System.err.print(ERROR_MESSAGE);
return;
}catch(IOException error){
System.err.print(ERROR_MESSAGE);
return;
}catch(ErrorException error){
System.err.print(error.getMessage());
return;
}
}
public class CommandFileParser {
public CommandFileParser (BufferedReader reader){
this.reader = reader;
}
/**
* read all lines from a file.
*
* #return a string array containing all file lines
*/
public String[] readFileLines(){
ArrayList<String> fileLines = new ArrayList<String>();
String textLine;
while ((textLine = this.reader.readLine()) != null){
fileLines.add(textLine);
}
String[] allFileLines = new String[fileLines.size()];
fileLines.toArray(allFileLines);
return allFileLines;
}
in the while loop I get a compilation error for unhandling the IOException.
How can I catch all exceptions in main,
and so the class takes only one string argument?
your readFileLines method is lacking a throws clause.
public String[] readFileLines() throws IOException {

How to do web scraping? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to get data from other site.
I want these items:
apple,anar,andi,arabi,Lucknow ,date
…from this site:
http://www.upmandiparishad.in/MWRates.asp
My original source code…
public class readURL {
public static void main(String[] args){
String generate_URL = "http://www.upmandiparishad.in/MWRates.asp";
try {
URL data = new URL(generate_URL);
URLConnection yc = data.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
My updated source code using the jsoup library…
public class parse3 {
public static void print(String url) throws IOException{
Document doc = Jsoup.connect(url).timeout(20*1000).get();
Element pending = doc.select("table td:eq(1)").first();
int nex=doc.select("table td:eq(0)").size();
//System.out.println(nex);
System.out.println(pending.text());
//System.out.println(nex);
}
public static void main(String[] args) throws IOException {
String url = "http://www.upmandiparishad.in/MWRates.asp";
new parse3().print(url);
}
}
You need to download the page and parse the html for the keywords you are looking for.
For this purpose, since you are using java use jsoup.
JSoup can download as well as retrieve the keywords you are looking for.
UPDATE
To get the rates of all the items you have to access the select tag.
Elements options = document.select("select#comcode > option");
for(Element element : options){
System.out.println("Price of " + element.text() + ":" + element.attr("value"));
}

Categories