remove "," from each line and put to arraylist in java - java
Content of a file:
Afganistan,5,1,648,16,10,2,0,3,5,1,1,0,1,1,1,0,green,0,0,0,0,1,0,0,1,0,0,black,green
Albania,3,1,29,3,6,6,0,0,3,1,0,0,1,0,1,0,red,0,0,0,0,1,0,0,0,1,0,red,red
Algeria,4,1,2388,20,8,2,2,0,3,1,1,0,0,1,0,0,green,0,0,0,0,1,1,0,0,0,0,green,white
American-Samoa,6,3,0,0,1,1,0,0,5,1,0,1,1,1,0,1,blue,0,0,0,0,0,0,1,1,1,0,blue,red
Andorra,3,1,0,0,6,0,3,0,3,1,0,1,1,0,0,0,gold,0,0,0,0,0,0,0,0,0,0,blue,red
Angola,4,2,1247,7,10,5,0,2,3,1,0,0,1,0,1,0,red,0,0,0,0,1,0,0,1,0,0,red,black
Anguilla,1,4,0,0,1,1,0,1,3,0,0,1,0,1,0,1,white,0,0,0,0,0,0,0,0,1,0,white,blue
I need to remove "," from the lines and put each line into an array separately.
The content of one line should be separate from other line using java
I used ArrayList but array includes commas.
Please help me remove "," from each line.
This is the code I have used so far:
String filePath = "/home/pavan/Desktop/flag.data";
try
{
BufferedReader lineReader = new BufferedReader(new FileReader(filePath));
String lineText = null;
List<String> listLines = new ArrayList<String>();
while ((lineText = lineReader.readLine()) != null)
{
String a = lineText.replaceAll(",", "");
listLines.add(a);
}
lineReader.close();
for (String line : listLines)
{
System.out.println(line);
}
}catch(IOException ex){
System.err.println(ex);
}
String [] newArray = yourString.split(",");
Related
Simplest way to concatenate multi lines of text in java through File Handling
I tried concatenating 2 lines of text in a given text file and printing the output to the console. My code is very complicated, is there a simpler method to achieve this by using FileHandling basic concepts ? import java.io.*; public class ConcatText{ public static void main(String[] args){ BufferedReader br = null; try{ String currentLine; br = new BufferedReader(new FileReader("C:\\Users\\123\\Documents\\CS105\\FileHandling\\concat.file.text")); StringBuffer text1 = new StringBuffer (br.readLine()); StringBuffer text2 = new StringBuffer(br.readLine()); text1.append(text2); String str = text1.toString(); str = str.trim(); String array[] = str.split(" "); StringBuffer result = new StringBuffer(); for(int i=0; i<array.length; i++) { result.append(array[i]); } System.out.println(result); } catch(IOException e){ e.printStackTrace(); }finally{ try{ if(br != null){ br.close(); } }catch(IOException e){ e.printStackTrace(); } } } } The text file is as follows : GTAGCTAGCTAGC AGCCACGTA the output should be as follows (concatenation of the text file Strings) : GTAGCTAGCTAGCAGCCACGTA
If you are using java 8 or newer, the simplest way would be: List<String> lines = Files.readAllLines(Paths.get(filePath)); String result = String.join("", lines); If you are using java 7, at least you can use try with resources to reduce the clutter in the code, like this: try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { StringBuffer text1 = new StringBuffer (br.readLine()); StringBuffer text2 = new StringBuffer(br.readLine()); // ... }catch(IOException e){ e.printStackTrace(); } This way, resources will be autoclosed and you don't need to call br.close().
Short answer, there is: public static void main(String[] args) { //this is called try-with-resources, it handles closing the resources for you try (BufferedReader reader = new BufferedReader(...)) { StringBuilder stringBuilder = new StringBuilder(); String line = reader.readLine(); //readLine() will return null when there are no more lines while (line != null) { //replace any spaces with empty string //first argument is regex matching any empty spaces, second is replacement line = line.replaceAll("\\s+", ""); //append the current line stringBuilder.append(line); //read the next line, will be null when there are no more line = reader.readLine(); } System.out.println(stringBuilder); } catch (IOException exc) { exc.printStackTrace(); } } First of all read on try with resources, when you are using it you don't need to close manually resources(files, streams, etc.), it will do it for you. This for example. You don't need to wrap read lines in StringBuffer, you don't get anything out of it in this case. Also read about the methods provided by String class starting with the java doc - documentation.
How to delete a line from text line by id java
How to delete a line from a text file java? I searched everywhere and even though I can't find a way to delete a line. I have the text file: a.txt 1, Anaa, 23 4, Mary, 3 and the function taken from internet: public void removeLineFromFile(Long id){ try{ File inputFile = new File(fileName); File tempFile = new File("C:\\Users\\...myTempFile.txt"); BufferedReader reader = new BufferedReader(new FileReader(inputFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); String lineToRemove = Objects.toString(id,null); String currentLine; while((currentLine = reader.readLine()) != null) { // trim newline when comparing with lineToRemove String trimmedLine = currentLine.trim(); String trimmLine[] = trimmedLine.split(" "); if(!trimmLine.equals(lineToRemove)) { writer.write(currentLine + System.getProperty("line.separator")); } } writer.close(); reader.close(); boolean successful = tempFile.renameTo(inputFile); }catch (IOException e){ e.printStackTrace(); } } where the fileName is the path for a.txt. I have to delete the line enetering the id.That's why I split the trimmedLine. At the end of execution I have 2 files, the a.txt and myTempFile both having the same lines(the ones from beginning). Why couldn't delete it?
If I understand your question correctly, you want to delete the line whose id matches with the id passed in the removeLineFromFile method. To make your code work, only few changes are needed. To extract the id, you need to split using both " " and "," i.e. String trimmLine[] = trimmedLine.split(" |,"); where | is the regex OR operator. See Java: use split() with multiple delimiters. Also, trimmLine is an array, you can't just compare trimmLine with lineToRemove. You first need to extract the first part which is the id from trimmLine. I would suggest you to look at the working of split method if you have difficulty in understanding this. You can have a look at How to split a string in Java. So, extract the id which is the first index of the array trimmLine here using: String part1 = trimmLine[0]; and then compare part1 with lineToRemove. Whole code looks like: public void removeLineFromFile(Long id){ try{ File inputFile = new File(fileName); File tempFile = new File("C:\\Users\\...myTempFile.txt"); BufferedReader reader = new BufferedReader(new FileReader(inputFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); String lineToRemove = Objects.toString(id,null); String currentLine; while((currentLine = reader.readLine()) != null) { // trim newline when comparing with lineToRemove String trimmedLine = currentLine.trim(); String trimmLine[] = trimmedLine.split(" |,"); String part1 = trimmLine[0]; if(!part1.equals(lineToRemove)) { writer.write(currentLine + System.getProperty("line.separator")); } } writer.close(); reader.close(); boolean successful = tempFile.renameTo(inputFile); }catch (IOException e){ e.printStackTrace(); } }
Java: Read from txt file and store each word only once in array + sorting
I am having a problem with my program. What i am supposed to do is: find all words from some txt files store each word in array only once Then sort alphabetically I dont know how to ensure that each word won't appear twice(or more) in my array. For example, a sentence from one of my files: My cat is huge and my dog is lazy. I want the words "my" and "is" to appear only once in my array, not twice. As for the sorting, is there anything that i can use from Java ? I don't know. Any help is appreciated! Here is what i have done so far: try { File dir = new File("path of folder that contains my files") for (File f : dir.listFiles()) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f))); String line = null; while((line = br.readLine())!= null) { String [] tokens = line.split(",\\s+|\\s*\\\"\\s*|\\s+|\\.\\s*|\\s*\\:\\s*"); } } }
Here is the modified code to have sorted unique words: try { TreeSet<String> uniqueSortedWords = new TreeSet<String>(); File dir = new File( "words.txt"); BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(dir))); String line = null; while ((line = br.readLine()) != null) { String[] tokens = line .split(",\\s+|\\s*\\\"\\s*|\\s+|\\.\\s*|\\s*\\:\\s*"); for(String token: tokens) { uniqueSortedWords.add(token); } } System.out.println(uniqueSortedWords); //call uniqueSortedWords.toArray() to have output in an array } catch (Exception e) { e.printStackTrace(); }
ifI guess you are looking for a code something like this. try { ArrayList<String> list = new ArrayList<String>(); File dir = new File("path of folder that contains my files") for (File f : dir.listFiles()) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f))); String line = null; while((line = br.readLine())!= null) { String [] tokens = line.split(",\\s+|\\s*\\\"\\s*|\\s+|\\.\\s*|\\s*\\:\\s*"); for(int i=0; i<tokens.length(); i++) { //Adding non-duplicates to arraylist if (!list.contains(tokens[i]) { list.add(tokens[i]); } } } Collections.Sort(list); } } catch(Exception ex){} Do not forget: import java.util.*; at the beginning of your code to use Collections.Sort(); EDIT Even though contains is a built-in method you can directly use with ArrayLists, this is how such a method works in fact (just in case if you are curious): public static boolean ifContains(ArrayList<String> list, String name) { for (String item : list) { if (item.getName().equals(name)) { return true; } } return false; } then to call it: ifContains(list, tokens[i]))
You can use the combination of HashSet and TreeSet Hashset:hashset allows null object. TreeSet:treeset will not allow null object,treeset elements are sorted in ascending order by default. Both HashSet and TreeSet does not hold duplicate elements. try { Set<String> list = new HashSet<>(); File f = new File("data.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f))); String line = null; while ((line = br.readLine()) != null) { String[] tokens = line.split(",\\s+|\\s*\\\"\\s*|\\s+|\\.\\s*|\\s*\\:\\s*");// other alternative:line.split("[,;-!]") for (String token : tokens) { list.add(token); } } // Add the list to treeSet;Elements in treeSet are sorted // Note: words must have the same case either lowercase or uppercase // for sorting to work correctly TreeSet<String> sortedSet = new TreeSet<>(); sortedSet.addAll(list); Iterator<String> ite = sortedSet.iterator(); while (ite.hasNext()) { System.out.println(ite.next()); } } catch (Exception e) { e.printStackTrace(); }
Java - Only read first line of a file
I only want to read the first line of a text file and put that first line in a string array. This is what I have but its reading the whole file. ex text in myTextFile: Header1,Header2,Header3,Header4,Header5 1,2,3,4,5 6,7,8,9,10 String line= System.getProperty("line.separator"); String strArray[] = new String[5]; String text = null; BufferedReader brTest = new BufferedReader(new FileReader(myTextFile)); text = brTest .readLine(); while (text != line) { System.out.println("text = " + text ); strArray= text.split(","); }
use BufferedReader.readLine() to get the first line. BufferedReader brTest = new BufferedReader(new FileReader(myTextFile)); text = brTest .readLine(); System.out.println("Firstline is : " + text);
If I understand you, then String text = brTest.readLine(); // Stop. text is the first line. System.out.println(text); String[] strArray = text.split(","); System.out.println(Arrays.toString(strArray));
With Java 8 and java.nio you can also do the following: String myTextFile = "path/to/your/file.txt"; Path myPath = Paths.get(myTextFile); String[] strArray = Files.lines(myPath) .map(s -> s.split(",")) .findFirst() .get(); If TAsks assumption is correct, you can realize that with an additional .filter(s -> !s.equals(""))
Also, beside of all other solutions presented here, you could use guava utility class (Files), like below: import com.google.common.io.Files; //... String firstLine = Files.asCharSource(myTextFile).readFirstLine();
I think you are trying to get one line only if it's not empty. You can use while ((text=brTest .readLine())!=null){ if(!text.equals("")){//Ommit Empty lines System.out.println("text = " + text ); strArray= text.split(","); System.out.println(Arrays.toString(strArray)); break; } }
Use this BuffereedReader reader = new BufferedReader(new FileReader(textFile)); StringBuilder builder = new StringBuilder(); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); break; } if(sb.toString.trim().length!=0) System.out.println("first line"+sb.toString);
I hope this will help someone to read the first line: public static String getFirstLine() throws IOException { BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")); String line = br.readLine(); br.close(); return line; } to read the whole text: public static String getText() throws IOException { BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line).append("\n"); line = br.readLine(); } String fileAsString = sb.toString(); br.close(); return fileAsString; }
You need to change the condition of your loop String[] nextLine; while((nextLine = brTest.readLine()) != null) { ... } ReadLine reads each line from beginning up to the occurrence of \r andor \n You can also use tokenizer to split the string String[] test = "this is a test".split("\\s"); In addition it seems the file is of type CSV if it is please mention that in the question.
Java - Create String Array from text file [duplicate]
This question already has answers here: Java: Reading a file into an array (5 answers) Closed 1 year ago. I have a text file like this : abc def jhi klm nop qrs tuv wxy zzz I want to have a string array like : String[] arr = {"abc def jhi","klm nop qrs","tuv wxy zzz"} I've tried : try { FileInputStream fstream_school = new FileInputStream("text1.txt"); DataInputStream data_input = new DataInputStream(fstream_school); BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input)); String str_line; while ((str_line = buffer.readLine()) != null) { str_line = str_line.trim(); if ((str_line.length()!=0)) { String[] itemsSchool = str_line.split("\t"); } } } catch (Exception e) { // Catch exception if any System.err.println("Error: " + e.getMessage()); } Anyone help me please.... All answer would be appreciated...
If you use Java 7 it can be done in two lines thanks to the Files#readAllLines method: List<String> lines = Files.readAllLines(yourFile, charset); String[] arr = lines.toArray(new String[lines.size()]);
Use a BufferedReader to read the file, read each line using readLine as strings, and put them in an ArrayList on which you call toArray at end of loop.
Based on your input you are almost there. You missed the point in your loop where to keep each line read from the file. As you don't a priori know the total lines in the file, use a collection (dynamically allocated size) to get all the contents and then convert it to an array of String (as this is your desired output). Something like this: String[] arr= null; List<String> itemsSchool = new ArrayList<String>(); try { FileInputStream fstream_school = new FileInputStream("text1.txt"); DataInputStream data_input = new DataInputStream(fstream_school); BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input)); String str_line; while ((str_line = buffer.readLine()) != null) { str_line = str_line.trim(); if ((str_line.length()!=0)) { itemsSchool.add(str_line); } } arr = (String[])itemsSchool.toArray(new String[itemsSchool.size()]); } Then the output (arr) would be: {"abc def jhi","klm nop qrs","tuv wxy zzz"} This is not the optimal solution. Other more clever answers have already be given. This is only a solution for your current approach.
This is my code to generate random emails creating an array from a text file. import java.io.*; public class Generator { public static void main(String[]args){ try { long start = System.currentTimeMillis(); String[] firstNames = new String[4945]; String[] lastNames = new String[88799]; String[] emailProvider ={"google.com","yahoo.com","hotmail.com","onet.pl","outlook.com","aol.mail","proton.mail","icloud.com"}; String firstName; String lastName; int counter0 = 0; int counter1 = 0; int generate = 1000000;//number of emails to generate BufferedReader firstReader = new BufferedReader(new FileReader("firstNames.txt")); BufferedReader lastReader = new BufferedReader(new FileReader("lastNames.txt")); PrintWriter write = new PrintWriter(new FileWriter("emails.txt", false)); while ((firstName = firstReader.readLine()) != null) { firstName = firstName.toLowerCase(); firstNames[counter0] = firstName; counter0++; } while((lastName= lastReader.readLine()) !=null){ lastName = lastName.toLowerCase(); lastNames[counter1]=lastName; counter1++; } for(int i=0;i<generate;i++) { write.println(firstNames[(int)(Math.random()*4945)] +'.'+lastNames[(int)(Math.random()*88799)]+'#'+emailProvider[(int)(Math.random()*emailProvider.length)]); } write.close(); long end = System.currentTimeMillis(); long time = end-start; System.out.println("it took "+time+"ms to generate "+generate+" unique emails"); } catch(IOException ex){ System.out.println("Wrong input"); } } }
You can read file line by line using some input stream or scanner and than store that line in String Array.. A sample code will be.. File file = new File("data.txt"); try { // // Create a new Scanner object which will read the data // from the file passed in. To check if there are more // line to read from it we check by calling the // scanner.hasNextLine() method. We then read line one // by one till all line is read. // Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); //store this line to string [] here System.out.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); }
Scanner scanner = new Scanner(InputStream);//Get File Input stream here StringBuilder builder = new StringBuilder(); while (scanner.hasNextLine()) { builder.append(scanner.nextLine()); builder.append(" ");//Additional empty space needs to be added } String strings[] = builder.toString().split(" "); System.out.println(Arrays.toString(strings)); Output : [abc, def, jhi, klm, nop, qrs, tuv, wxy, zzz] You can read more about scanner here
You can use the readLine function to read the lines in a file and add it to the array. Example : File file = new File("abc.txt"); FileInputStream fin = new FileInputStream(file); BufferedReader reader = new BufferedReader(fin); List<String> list = new ArrayList<String>(); while((String str = reader.readLine())!=null){ list.add(str); } //convert the list to String array String[] strArr = Arrays.toArray(list); The above array contains your required output.