I have a method that reads from a URL and splits the text into sentences using a delimiter. Here's what I have:
try {
URL url = new URL("Some link");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String l;
while((l = in.readLine()) != null) {
String sentence = l.replaceAll("[^a-zA-Z?.!]"," ");
String[] sent = sentence.split("[?.!]", 2);
for(int x = 0; x < sent.length; x++) {
System.out.println(sent[x]);
}
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
This prints out the text sentence by sentence. However, I would like to read 30 sentences at a time, just wondering how I would go about doing that.
Use a StringBuilder to concatenate the whole text to work with first, then split it with a point and finally loop over it 50 times printing the 50 first indexes of the whole text array.
StringBuilder sb = new StringBuilder();
while((l = in.readLine()) != null) {
sb.append(l);
}
String[] sentences = sb.toString().split(".");
for (int i = 0 ; i < 50 ; i++){
System.out.println(sentences[i]);
}
Related
protected synchronized static void getRandomProxy(String srcFile) throws FileNotFoundException {
List<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
System.out.println(line);
}
int k = 0;
for (int i = 0; i < words.size(); i++) {
k++;
String[] splitted = words.get(i).split(":");
String ip = splitted[0];
String port = splitted[splitted.length - 1];
// System.out.println(k + " " + ip + " * " + port);
}
} catch (IOException iOException) {
} finally {
try {
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I want to get output printed without empty lines .
These are kind of results am getting Like :
result 1.
result 2.
result 3.
i want output like :
result 1.
result 2.
result 3.
without blank lines.
Don't add the String to the list if it's empty :
if(!line.trim().isEmpty()) {
words.add(line);
System.out.println(line);
}
If you still want to add the blank lines to the list but don't display them, just move the condition :
words.add(line);
if(!line.trim().isEmpty())
System.out.println(line);
Doc
Use System.out.print. Note that the file contains a newline char at the end of each line.
If srcFile is created with Notepad, try removing first the carriage return char System.out.print(line.replaceAll("\\r",""))
ArrayList<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim(); // remove leading and trailing whitespace
if (!line.isEmpty() && !line.equals("")) {
words.add(line);
System.out.println(line);
}
}
I'm having a small problem with my code and I'm not exactly sure how to fix it.. Basically I'm trying to separate the file into different lines (Frames) and then input those lines into the file, and proceed to print them. My first line of the file never prints.
public class Main {
public static void main(String[] args) throws IOException
{
/*Switch switcherino = new Switch();*/
Frame frame = new Frame();
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the file to process: ");
String fileName = input.nextLine();
FileInputStream inputStream =
new FileInputStream(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(inputStream,Charset.forName("UTF-8"));
BufferedReader bufferedReader =
new BufferedReader(inputStreamReader);
try{
String str = " ";
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
}
catch (IOException e){
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
I don't want to use an ArrayList, as much as it would probably be easier.
Thanks in advance!
File: (switch.txt)
fa00 123123123abc 111111222222 data1
fa01 111111222222 123123123abc data2
fa03 444444444444 123123123abc data3
fa01 123123123abc 4353434234ab data4
fa99 a11b22c33d44 444444444444 data5
Output: (from System.println(words[i]);)
fa01 111111222222 123123123abc data2
fa03 444444444444 123123123abc data3
fa01 123123123abc 4353434234ab data4
fa99 a11b22c33d44 444444444444 data5
This is wrong logic: you read the line, you split it into words so then go ahead and print them - no need to try and read any more lines
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
use this instead
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
System.out.println(words[i]);
}
}
// to count length
int length = 0;
BufferedReader br =
new BufferedReader(inputStreamReader);
while(true){
str = br.readLine();
if(str == null) break;
else length++;
} // this loop counts the length!!
final int clength = length;
//now this is what you want!
String words[] = new String[clength];
int j= 0;
while(true){
str = bufferedReader.readLine();
if(str == null) break;
words[j++] = str;
System.out.println(str); //FIXED
}
//Now the words[] have all the lines individually
Your code doesn't work because you called readLine() twice, which skipped the first line. Try this and let me know.
You don't need to use split() since you want the entire line :)
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
When iterate the file, you split your first line into a String array,
words[] contains the following elements : fa00, 123123123abc, 111111222222 and data1.
and then the inner for loop iterate your bufferReader and you assign the lines to a specific index of word and then you print out the word array elements
You are not supposed to invoke bufferedReader.readLine() in the inner for loop, it breaks your logic.
I have a Justice_League.csv file that has four lines with commas between them. I want to count the number of characters there are in each line and convert that number to hex.
Below is the contents of Justice_League.csv:
Bruce Wayne,Batman,None,Gotham City,Robin,The Joker 43 2B
Oliver Queen,Green Arrow,None,Star City,Speedy,Deathstroke 50 32
Clark Kent,Superman,Flight,Metropolis,None,Lex Luthor 46 2E
Bart Allen,The Flash,Speed,Central City,Kid Flash,Professor Zoom 52 34
As you can see I have handcounted the characters and wrote the HEX value next to it. Now I need this done in Java. This is what I have so far. Can anybody help me out?
public String convertCSVToFlat (Exchange exchange) throws Exception {
String csv="Justice_League.csv";
BufferedReader bReader = new BufferedReader(new FileReader(csv));
String line = "";
int count = 0;
String str[] = new String[200];
int[] a = new int[24];
String[] hexNumber = new String[4];
try {
bReader.readLine();
int characterSum = 0;
int i = 0;
while((line = bReader.readLine()) != null) {
String[] f=line.split(",");
a[count]=Integer.parseInt(f[2]);
str[count]=f[1];
count++;
characterSum += line.length();
hexNumber[i] = Integer.toHexString(characterSum);
i++;
}
} catch (IOException e) {
e.printStackTrace();
}
bReader.close();
return hexNumber.toString();
I suggest you to read the javadoc of String.split. I think that you misunderstood the concept when you did this:
String[] f=line.split(",");
a[count]=Integer.parseInt(f[2]); //--> java.lang.NumberFormatException here!
Avoid using 'magic' numbers in your code like int[] a = new int[24];. Why 24?
Well, here comes a version that do what you want to do. Maybe it isn't the best way to do this but it works.
public void convertCSVToFlat () throws Exception {
String csv="Justice_League.csv";
BufferedReader bReader = new BufferedReader(new FileReader(csv));
//We're storing the values at this 3 arraylists,
//but a better approach is using an object to hold'em
ArrayList<String> lines = new ArrayList<String>();
ArrayList<Integer> chars = new ArrayList<Integer>();
ArrayList<String> hex = new ArrayList<String>();
String line = "";
try {
while((line = bReader.readLine()) != null) {
lines.add(line);
//I'm assuming that you don't want to count the commas and spaces.
//If you want to, comment the next line
line = line.replaceAll(",", "").replaceAll(" ", "");
int c = line.length(); //count remaining chars...
chars.add(c);
hex.add(Integer.toHexString(c));
}
} catch (IOException e) {
e.printStackTrace();
}
bReader.close();
//Just to show the results
for (int i = 0; i < lines.size(); i++) {
System.out.print(lines.get(i));
System.out.print("\t" + chars.get(i));
System.out.println("\t" + hex.get(i));
}
}
Like I said previously, this is a way to solve this. You should try another options to solve this in order to improve your knowledge...
My proccesos.txt has this
1,500,600
2,300,800
3,800,1000
4,200,5000
What im trying to do here is insert the procesos.txt in a 2d array that will be displaying as follow 4 rows with 3 columns but without the comamas
This is currently my code on the buttom
`
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\Ifrahim\\Desktop\\Procesos.txt"));
br2 = new BufferedReader(new FileReader("C:\\Users\\Ifrahim\\Desktop\\Procesos.txt"));
int lines = (int) br2.lines().count();
myArr = new int[lines][3];
String[] lineArray = null ;
while ((sCurrentLine = br.readLine()) != null) {
lineArray=sCurrentLine.split(",");
System.out.println(Arrays.toString(lineArray));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
`
int line = 0;
while((sCurrentLine = br.readLine()) != null){
String[] tmp = sCurrentLine.split(",");//split the line up into its separate values
for(int i = 0 ; i < 3 ; i++)
myArr[line][i] = Integer.parseInt(tmp[i]);
//convert the values into integers and insert them at the matching position
//in the array
line++;
}
Hello all I am trying to scan the bottom 6 lines of a text file and display them in a JOptionPane.showMessageDialog currently it is being displayed as [line7, line6, line5, line4, line3, line2] I would prefer it to be displayed as a vertical list instead of the comma seperator.
ArrayList<String> bandWidth = new ArrayList<String>();
FileInputStream in = null;
try {
in = new FileInputStream("src/list.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String tmp;
try {
while ((tmp = br.readLine()) != null)
{
bandWidth.add(tmp);
if (bandWidth.size() == 7)
bandWidth.remove(0);
}
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> reversedSix = new ArrayList<String>();
for (int i = bandWidth.size() - 1; i >= 0; i--)
reversedSix.add(bandWidth.get(i));
JOptionPane.showMessageDialog(null,bandWidth,null,JOptionPane.INFORMATION_MESSAGE);
Try looping the ArrayList and produce a String with new line characters:
String result = "";
for (int i = 0; i < bandWidth.size(); i++)
{
result += bandWidth.get(i) + "\n";
}
JOptionPane.showMessageDialog(null,result ,null,JOptionPane.INFORMATION_MESSAGE);
Note: if this is outputting HTML, then use <br \> instead of \n.