Empty line in arraylist Java - java

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);
}
}

Related

Array returning null

I'm trying to read into a csv file and placing the line into an array. But when I print the array out it is null.
Here is the code:
public static String[] readFile(String inFilename)
{
int lineTotal = getLineNum(inFilename);
if (lineTotal == 0)
{
System.out.println("The file is empty ");
}
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String[] resultArrayOne = new String[lineTotal + 1];
String line;
try
{
fileStrm = new FileInputStream(inFilename); //open file
rdr = new InputStreamReader(fileStrm); //create a reader to read the stream
bufRdr = new BufferedReader(rdr);//read file line by line
int lineNum;
String[] resultArray = new String[lineTotal];
String info;
lineNum = 0;
while ((line = bufRdr.readLine()) != null) //While not end-of-file, process and read lines
{
info = line;
System.out.println(info);
resultArray[lineNum] = info;
lineNum++;
}
fileStrm.close(); //Clean up the stream
resultArrayOne = resultArray;
}
catch (IOException e) // MUST catch IOExceptions
{
if (fileStrm != null) //Clean up the stream if it was opened
{
try
{
fileStrm.close();
}
catch (IOException ex2) { } // We can’t do anything more!
}
System.out.println("Error in file processing: " + e.getMessage()); //Or do a throw
}
return resultArrayOne;
}
When printing out the line before placing it into the array the return is fine, but when placed into the array it become null.
edit:
Here is the full FileIO code:
public static String[] Import()
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the File Name: ");
String fileName = sc.nextLine();
int length = getLineNum(fileName);
String[] array = new String[length+1];
array = readFile(fileName);
return array; //array is just strings
}
public static int getLineNum(String inFilename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
int lineNum = 0;
try
{
fileStrm = new FileInputStream(inFilename); //open file
rdr = new InputStreamReader(fileStrm); //create a reader to read the stream
bufRdr = new BufferedReader(rdr);//read file line by line
lineNum = 0;
while ((line = bufRdr.readLine()) != null) //While not end-of-file, process and read lines
{
lineNum++;
}
fileStrm.close(); //Clean up the stream
}
catch (IOException e) // MUST catch IOExceptions
{
if (fileStrm != null) //Clean up the stream if it was opened
{
try
{
fileStrm.close();
}
catch (IOException ex2) { } // We can’t do anything more!
}
System.out.println("Error in file processing: " + e.getMessage()); //Or do a throw
}
return lineNum;
}
I'm not too sure how to insert a sample file but it is something like this:
SHOP1, STORE2, 45
SHOP2, SHOP1, 67
STORE6, SHOP1, 90
...
edit 2:
I added the code that uses this
String[] locationArrayOne = new String[1000];
locationArrayOne = FileIO.Import();
for (int yyy = 0; yyy < locationArrayOne.length; yyy++)
{
System.out.print(locationArray[yyy]);
}
Your code looks fine but here is how I would debug the problem:
Before lineNum++, I will print the value of resultArray[lineNum] instead of info to see if the program was able to retrieve the line and store it to the array.
Remove the initialization of String[] resultArrayOne and after fileStrm.close(), use resultArrayOne = resultArray.clone() to copy the values of resultArray to resultArrayOne. Copying an array by assignment (array1 = array2) could have side-effects you do not want in your program since you are making both arrays refer to the same object. Check this related question here
Also, why not use resultArrayOne directly when storing the lines?

Sorting a Java String Array with a pattern

I am currently reading and writing to a text file and I cant figure out a way to sort. I thought I would be able to sort by pattern. I would like to sort a java string array by the pattern (0-9, A-Z, a-z). Basically I would like to ignore non-alphanumeric characters, sort with numbers preceding letters, and capital letters preceding lowercase letters (i.e., 0-9, A-Z, a-z). I would like to remove lines that only have non-alphanumeric characters.
File f1 = new File(fp);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
count++;
// SORT GOES HERE
if (line.contains(sx)) {
line = line.replace(line, "");
}
if (yint > 0 && !line.isBlank()) {
line = line.substring(yint);
}
if(!line.isBlank()){
line = line.replace(line, count + " " + line + "\n");
lines.add(line);
} else {
lines.add(line);
}
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
I would likely use something like Collections.sort() at the end and a simple check in the loop:
File f1 = new File(fp);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
count++;
if (!line.matches("[a-zA-Z0-9]+")) {
continue;
}
if (line.contains(sx)) {
line = line.replace(line, "");
}
if (yint > 0 && !line.isBlank()) {
line = line.substring(yint);
}
if(!line.isBlank()){
line = line.replace(line, count + " " + line + "\n");
lines.add(line);
} else {
lines.add(line);
}
}
fr.close();
br.close();
Collections.sort(lines, (a, b) -> {
String aNum = a.replaceAll("[^a-zA-Z0-9]", "");
String bNum = b.replaceAll("[^a-zA-Z0-9]", "");
return a.compareTo(b);
});
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
EDIT: You can certainly make this work faster/better by quick-checking perhaps in the sort, etc - but generally this is the idea I think
You can't sort the file while you are reading it, in your case it needs to be done before:
// Sort the file
Path initialFile = Paths.get("myFile.txt");
List<String> sortedLines = Files.lines(initialFile)
.sorted()
.collect(Collectors.toList());
// Process the sorted lines
List<String> lines = new ArrayList<String>();
int count=0;
for(String line : sortedLines) {
System.out.println("l: "+line);
count++;
if (line.contains(sx)) {
line = line.replace(line, "");
}
if (yint > 0 && !line.isEmpty()) {
line = line.substring(yint);
}
if (!line.isEmpty()) {
System.out.println("line:"+line);
line = line.replace(line, count + " " + line + "\n");
System.out.println("new line:"+line);
lines.add(line);
} else {
System.out.println("add:"+line);
lines.add(line);
}
}
// Write output file
File f1 = new File("myFile.txt");
try(BufferedWriter out = new BufferedWriter( new FileWriter(f1))){
for (String s : lines)
out.write(s);
}
Try this.
static void sortByAlphaNumeric(String inFile, String outFile) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(inFile)).stream()
.map(line -> new Object() {
String sortKey = line.replaceAll("[^0-9A-Za-z]", "");
String originalLine = line;
})
.filter(obj -> !obj.sortKey.equals(""))
.sorted(Comparator.comparing(obj -> obj.sortKey))
.map(obj -> obj.originalLine)
.collect(Collectors.toList());
Files.write(Paths.get(outFile), lines);
}

Printing Sentences in Java

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]);
}

Java - Splitting ArrayList

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.

Read file and insert data into String[]

public static String[] words = null;
public static String readFile(String name) {
int i = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(name));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
i++;
sb.append(sb.toString());
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
words = everything.split("\\n");//not sure if this is right...
} finally {
br.close();
}
} catch (Exception e) {
e.getMessage();
}
return "Loaded " + i + " words";
}
I'm basically trying to read a file with data on each line. On each line in the file I'm trying to insert into the array. May someone help me figure out what I'm doing wrong here?
The problem is that:
while (line != null) {
i++;
sb.append(sb.toString());
sb.append("\n");
line = br.readLine();
}
sb is never actually appended anything, it is just appending empty strings over and over again.
should be:
while (line != null) {
i++;
sb.append(line);
sb.append("\n");
line = br.readLine();
}

Categories

Resources