Scanner sc = new Scanner("textfile.txt");
List<String> tokens = new ArrayList<String>();
for (int i =0 ; sc.hasNextLine(); i++)
{
String temp = sc.nextLine();
tokens.add(temp);
}
My textfile looks something like
A
B
C
*empty line*
D
E
F
*empty line*
and so on..
The trouble I'm having is I'm trying to store each section to an array (including the empty line), but I don't know how to go about splitting up these sections. By section I mean A B C empty line, is one section.
If you are just splitting it at new lines and not white spaces, which is what it seems to be since you are using hasNextLine() and nexLine(), you can try this.
final String NEW_LINE = System.getProperty("line.separator");
Scanner sc = new Scanner(new File("textfile.txt"));
List<String> tokens = new ArrayList<String>();
StringBuilder builder = new StringBuilder();
while(sc.hasNextLine()) {
//Read the next line
String temp = sc.nextLine();
builder.append(temp);
if(temp.trim().equals("")) {
tokens.add(builder.toString() + NEW_LINE); //Copy the gotten tokens to the list adding a new line since we read up to, not including, the new line
builder = new StringBuilder(); //Clear the builder
}
}
//Copy any remaining characters to the list
tokens.add(builder.toString() + NEW_LINE);
Instead of adding every line to list as you read from file,
append to string builder or temporary string. When you detect new line, after appending it to temporary string or string builder, add all you got so far into list. Repeat until you have lines.
See complete example as asked Originally :
package com.raj;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Echo {
public static void main(String[] args) throws Exception {
Scanner sc
= new Scanner(new File("textfile.txt"));
List<StringBuilder> tokens
= new ArrayList<StringBuilder>();
StringBuilder builder
= new StringBuilder();
boolean saveFlag = true;
while (sc.hasNextLine()) {
String temp = sc.nextLine();
if (temp.isEmpty()) {
tokens.add(builder);
builder = new StringBuilder();
saveFlag = false;
continue;
}
builder.append(temp + "\n");
saveFlag = true;
}
sc.close();
if (saveFlag) tokens.add(builder);
for (StringBuilder sb : tokens) {
System.out.println(sb);
}
}
}
Related
import java.util.*;
import java.io.*;
public class readFiles2 {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new FileReader("someFile.txt"));
try{
StringBuilder text = new StringBuilder();
String readStringLine = reader.readLine();
String[] lines= {};
for(int i = 0; readStringLine != null; i++){
readStringLine = reader.readLine();
//Trying to save seperate lines of text in an array.
lines[i] = readStringLine.toString();
}
}
finally{
reader.close();
}
}
So what I'm trying to do is save separate lines of strings from a .txt file to a String[] array. I'm kind of at a loss right now and don't really know what else I can do.
Since you don't know how many strings there are for your array, you might want to put the strings in a list and convert to an array at the end:
String readStringLine;
List<String> lines = new ArrayList<String>();
while((readStringLine = reader.readLine()) != null) {
lines.add(readStringLine);
}
String[] linesArray = lines.toArray(new String[lines.size()]);
Edit: Simpified to use a while loop to gather the line from the reader.
ArrayList<String> line = new ArrayList<>();
FileReader file = new FileReader(file.txt);
BufferedReader reader = new BufferedReader(file);
while (reader.ready()) {
line.add(reader.readLine());
reader.close();
file.close();
}
To acess, use line.get(i); where i>=0 and i<=array.size
Using autocloseable interface and Java 8 streams:
String [] stringsArray = null;
try(BufferedReader br = new BufferedReader(new FileReader("someFile.txt"))) {
List<String> strings = new ArrayList<>();
br.lines().forEach(c -> strings.add(c));
stringsArray = strings.toArray(new String[strings.size()]);
}
You need Java 8 to run this code
So I have to extract data from a text file.
The text file is set up like this.
3400 Moderate
310 Light
etc.
I need to extract the numbers, store them in one array, and the strings, and store them in another array so I can do calculations to the numbers based on whats written in the array, and then output that to a file. I've got the last part down, I just cant figure out how to separate the ints from the strings when I extract the data from the txt. file.
Here is what I have now, but it's just extracting the int and the word as a String.
import java.io.*;
import java.util.*;
public class HorseFeed {
public static void main(String[] args){
Scanner sc = null;
try {
sc = new Scanner(new File("C:\\Users\\Patric\\Desktop\\HorseWork.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = lines.toArray(new String[0]);
for(int i = 0; i< 100; i++){
System.out.print(arr[i]);
}
}
}
Use split(String regex) in String class. Set the regex to search for whitespaces OR digits. It will return a String[] which contains words.
If you are analyzing it line by line, you would want another String[] in which you would append all the words from the new lines.
plz, follow the code.
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HorseFeed {
public static void main(String[] args) throws FileNotFoundException, IOException {
List<String> lineList = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(new File("C:\\Users\\Patric\\Desktop\\HorseWork.txt")));
String line;
while ((line = br.readLine()) != null) {
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(line);
if( pattern.matcher(line).matches()){
while(matcher.find()){
lineList.add(matcher.group());
}
}
}
}
}
here lineList contains your integer.
This should work:
import java.io.*;
import java.util.*;
public class HorseFeed {
public static void main(String[] args) throws FileNotFoundException {
List<Integer> intList = new ArrayList<Integer>();
List<String> strList = new ArrayList<String>();
Scanner sc = new Scanner(new File("C:\\Users\\Patric\\Desktop\\HorseWork.txt"));
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] lineParts = line.split("\\s+");
Integer intValue = Integer.parseInt(lineParts[0]);
String strValue = lineParts[1];
intList.add(intValue);
strList.add(strValue);
}
System.out.println("Values: ");
for(int i = 0; i < intList.size(); i++) {
System.out.print("\t" + intList.get(i) + ": " + strList.get(i));
}
}
}
First extract all text of file and stored it into String . then use replaceall method of string class with pattern to remove digits from it.
Example:
String fileText = new String("welcome 2 java");
ss = fileText.replaceAll("-?\\d+", "");
System.out.println(ss);
Using a scanner to read a line of input. I thought there was a way to directly insert the line into an array and have it separate into string elements (divided by spaces).
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numberOfStudents = input.nextInt();
input.nextLine();
String[][] partners = new String[2][numberOfStudents];
partners[1] = input.nextLine();
}
}
I attempted to rewrite your code to possibly be what you want. Could you try to specify exactly what you're trying to do?
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numberOfStudents = input.nextInt();
//input.nextLine();
String[][] partners = new String[2][numberOfStudents];
for(int i=0; i<numberOfStudents; i++)
{
partners[1][i] = input.nextLine();
}
}
}
I think you're looking for split.
For example:
String val="I am a String";
String [] tabDelimitedVals=val.split(" ");
This is seen in the stack overflow post here:
How to split a string in Java
To read from a file, you can use
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
The above was taken from: Reading a plain text file in Java
Together, you can do:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
String val=br.readLine();
String [] splitted=val.split(" ");
}
finally {
br.close();
}
I need to create a method that will read the file, and check each word in the file. Each new word in the file should be stored in a string array. The method should be case insensitive. Please help.
The file says the following:
Ask not what your country can do for you
ask what you can do for your country
So the array should only contain: ask, not, what, your, country, can, do, for, you
import java.util.*;
import java.io.*;
public class TextAnalysis {
public static void main (String [] args) throws IOException {
File in01 = new File("a5_testfiles/in01.txt");
Scanner fileScanner = new Scanner(in01);
System.out.println("TEXT FILE STATISTICS");
System.out.println("--------------------");
System.out.println("Length of the longest word: " + longestWord(fileScanner));
System.out.println("Number of words in file wordlist: " );
countWords();
System.out.println("Word-frequency statistics");
}
public static String longestWord (Scanner s) {
String longest = "";
while (s.hasNext()) {
String word = s.next();
if (word.length() > longest.length()) {
longest = word;
}
}
return (longest.length() + " " + "(\"" + longest + "\")");
}
public static void countWords () throws IOException {
File in01 = new File("a5_testfiles/in01.txt");
Scanner fileScanner = new Scanner(in01);
int count = 0;
while(fileScanner.hasNext()) {
String word = fileScanner.next();
count++;
}
System.out.println("Number of words in file: " + count);
}
public static int wordList (int words) {
File in01 = new File("a5_testfiles/in01.txt");
Scanner fileScanner = new Scanner(in01);
int size = words;
String [] list = new String[size];
for (int i = 0; i <= size; i++) {
while(fileScanner.hasNext()){
if(!list[].contains(fileScanner.next())){
list[i] = fileScanner.next();
}
}
}
}
}
You could take advantage of my following code snippet (it will not store the duplicate words)!
File file = new File("names.txt");
FileReader fr = new FileReader(file);
StringBuilder sb = new StringBuilder();
char[] c = new char[256];
while(fr.read(c) > 0){
sb.append(c);
}
String[] ss = sb.toString().toLowerCase().trim().split(" ");
TreeSet<String> ts = new TreeSet<String>();
for(String s : ss)
ts.add(s);
for(String s : ts){
System.out.println(s);
}
And the output is:
ask
can
country
do
for
not
what
you
your
You could always just try:
List<String> words = new ArrayList<String>();
//read lines in your file all at once
List<String> allLines = Files.readAllLines(yourFile, Charset.forName("UTF-8"));
for(int i = 0; i < allLines.size(); i++) {
//change each line from your file to an array of words using "split(" ")".
//Then add all those words to the list "words"
words.addAll(Arrays.asList(allLines.get(i).split(" ")));
}
//convert the list of words to an array.
String[] arr = words.toArray(new String[words.size()]);
Using Files.readAllLines(yourFile, Charset.forName("UTF-8")); to read all the lines of yourFile is much cleaner than reading each individually. The problem with your approach is that you're counting the number of lines, not the number of words. If there are multiple words on one line, your output will be incorrect.
Alternatively, if you do not use Java 7, you can create a list of lines as follows and then count the words at the end (as opposed to your approach in countWords():
List<String> allLines = new ArrayList<String>();
Scanner fileScanner = new Scanner(yourFile);
while (fileScanner.hasNextLine()) {
allLines.add(scanner.nextLine());
}
fileScanner.close();
Then split each line as shown in the previous code and create your array. Also note that you should use a try{} catch block around your scanner rather than throws ideally.
Say the following is my file content (hundreds of same pattern lines)
1979,2013-08-07 19:03:35,abc,12345,310012
1980,2013-08-07 19:05:03,fds,12345,310160
.
.
I want to read the file and scan the file line by line and replace the 4th column of the line (12345 which repeats on all the lines) to another value as well as adding a new value at the end of each line.
Finally I need to regenerate the file with the updated values as an output.
here is what I do so far:
URL path = ClassLoader.getSystemResource("test.txt");
File file = new File(path.toURI());
try
{
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
// Here I need to do the replacement codes
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Is it a good idea to split each line to an array and do the processes like that or is there any better solution for this?
I am also not sure how to create an output with the edited content.
Any help would be appreciated.
You could try something like this:
public void replace(final int column, final String replacement, final File file, final String... appends) throws IOException {
assert column >= 0 : "column < 0";
final List<String> lines = new LinkedList<String>();
final Scanner reader = new Scanner(file, "UTF-8");
while(reader.hasNextLine()){
final String line = reader.nextLine().trim();
if(line.isEmpty())
continue;
final String[] tokens = line.split(",");
assert column < tokens.length-1 : "column > tokens.length-1";
tokens[column] = replacement;
final StringBuilder builder = new StringBuilder();
for(final String token : tokens)
builder.append(token + ",");
for(final String append : appends)
builder.append(append + ",");
builder.deleteCharAt(builder.length()-1);
lines.add(builder.toString());
}
reader.close();
final BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
for(final String line : lines){
writer.write(line);
writer.newLine();
}
writer.flush();
writer.close();
}
Or if you are using Java 8, you could try something like this:
public void replace(final int column, final String replacement, final File file, final String... appends) throws IOException {
assert column >= 0 : "column < 0";
final List<String> lines = new LinkedList<>();
final Scanner reader = new Scanner(file, "UTF-8");
while(reader.hasNextLine()){
final String line = reader.nextLine().trim();
if(line.isEmpty())
continue;
final String[] tokens = line.split(",");
assert column < tokens.length-1 : "column > tokens.length-1";
tokens[column] = replacement;
final List<String> temp = new LinkedList<>();
temp.addAll(Arrays.asList(tokens));
temp.addAll(Arrays.asList(appends));
lines.add(temp.stream().collect(Collectors.joining(",")));
}
reader.close();
final BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
lines.forEach(
l -> {
try{
writer.write(l);
writer.newLine();
}catch(IOException ex){
ex.printStackTrace();
}
}
);
writer.flush();
writer.close();
}
To call this method, you could do something like this:
replace(3, "string to replace 12345", file, strings_you_want_to_append_to_the_end);
I'd do this by putting each line into an arraylist, using split(",") on each line of the array, and replacing the 4th index in each array. To rejoin the array back into a string, you'd have to write your own function (Java doesn't have one built-in). There is another stack overflow question that addresses this problem, though.
try
{
Scanner scanner = new Scanner(file);
// initialize the arraylist, which will hold the split strings
ArrayList<String[]> data = new ArrayList<String[]>();
while (scanner.hasNextLine())
{
// filling the arraylist
String line = scanner.nextLine();
String[] split = line.split(",");
data.add(split);
}
scanner.close();
// replacing the values
for (String[] split : data) {
split[3] = "new value";
}
// sloppily glueing everything back together
String output = "";
for (String[] split : data) {
for (int i = 0; i < 5; i++) {
if (i < 4) {output += datum + ",";}
else {output += datum;}
}
output += "\n";
}
return output;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Probably really sloppy and inefficient, but it's pretty logical.
You can do that with a regular expression:
(?<=^[^,]+,[^,]+,[^,]+,)[^,]+
e.g.:
private static final Pattern REGEX_PATTERN =
Pattern.compile("(?<=^[^,]+,[^,]+,[^,]+,)[^,]+");
public static void main(String[] args) {
// Open input file
// Open output file
// Read input line
String inputLine = "1979,2013-08-07 19:03:35,abc,12345,310012";
String outputLine = REGEX_PATTERN.matcher(input)
.replaceFirst("YOUR_REPLACEMENT");
// Print (only for debug)
System.out.println(
outputLine
); // prints "1979,2013-08-07 19:03:35,abc,YOUR_REPLACEMENT,310012"
// Write output line
// Close both files
}
Try the following
stringBuilder = new StringBuilder();
String[] resultArray = sCurrentval.split(",");
resultArray[3] = EDIT_VALVE; //your new value to replace
for (String s : resultArray)
{
stringBuilder.append(s);
stringBuilder.append(",");
}
sCurrentval = stringBuilder.append(LAST_VALUE).toString(); // add your last value