I read the content of one file into String(char[]) content:
8264,1
28462,1
15836,1
Then I want to multiply second column by 5 and append another file with processed values:
8264,5
28462,5
15836,5
The problem is with iterating over content. If I iterate as shown below, then obviously I get chars like 8, 2, 6, 4, etc., but not lines 8264,5.
FileWriter fw = new FileWriter(filew.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
StringBuilder sb = new StringBuilder();
for (int k = 0; k < content.length(); k++)
{
char c = content.charAt(k);
//multiply second column by 5
}
If you want to iterate line by line I would recommend a Scanner.
PrintWriter pw = new PrintWriter(...file/stream...);
Scanner sc = new Scanner(...your file/stream/string...);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] parts = line.split(",");
int first = Integer.parseInt(parts[0]);
int second = Integer.parseInt(parts[1]);
second *= 5;
pw.println(first + "," + second);
}
sc.close();
pw.close();
Related
I want to copy the last word of each line in a file 1 and put it in each line of the file 2.
file 1
x n o n
y n n o
z n n n
file 2
n, n, n, B-S
n, o, o, I-S
n, n, n, S
Output
x n o n B-S
y n n o I-S
z n n n S
My code
File f = new File("C:\\file.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
File f1 = new File("C:\\file1.txt");
BufferedReader reader1 = new BufferedReader(new FileReader(f1));
String line = null;
String line1 = null;
while ((line1 = reader1.readLine())!= null) {
String c = line1.substring(line1.lastIndexOf(" ")+1);
while((line = reader.readLine()) != null) {
FileWriter fileWritter = new FileWriter(f.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(c);
bufferWritter.close();
}
}
Since you seem to know how to read and write into files i leave you a simple code to get the last word of each line in a String. Just basic split here :
String input1 = "x n o n\ny n n o\nz n n n";
String input2 = "n, n, n, B-S\nn, o, o, I-S\nn, n, n, S";
String[] input1Lines = input1.split("\n");
String[] input2Lines = input2.split("\n");
String result = "";
for(int i=0; i<input2Lines.length; i++) {
String[] words = input2Lines[i].split(", ");
String lastWord = words[words.length-1];
result += input1Lines[i] + " " + lastWord + "\n";
}
System.out.println(result);
I have the following code which counts and displays the number of times each word occurs in the whole text document.
try {
List<String> list = new ArrayList<String>();
int totalWords = 0;
int uniqueWords = 0;
File fr = new File("filename.txt");
Scanner sc = new Scanner(fr);
while (sc.hasNext()) {
String words = sc.next();
String[] space = words.split(" ");
for (int i = 0; i < space.length; i++) {
list.add(space[i]);
}
totalWords++;
}
System.out.println("Words with their frequency..");
Set<String> uniqueSet = new HashSet<String>(list);
for (String word : uniqueSet) {
System.out.println(word + ": " + Collections.frequency(list,word));
}
} catch (Exception e) {
System.out.println("File not found");
}
Is it possible to modify this code to make it so it only counts each occurrence once per line rather than in the entire document?
One can read the contents per line and then apply logic per line to count the words:
File fr = new File("filename.txt");
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
// Read the line in the file
String line = null;
while ((line = br.readLine()) != null) {
//Code to count the occurrences of the words
}
Yes. The Set data structure is very similar to the ArrayList, but with the key difference of having no duplicates.
So, just use a set instead.
In your while loop:
while (sc.hasNext()) {
String words = sc.next();
String[] space = words.split(" ");
//convert space arraylist -> set
Set<String> set = new HashSet<String>(Arrays.asList(space));
for (int i = 0; i < set.length; i++) {
list.add(set[i]);
}
totalWords++;
}
Rest of the code should remain the same.
I am trying to create a program in Java that reads from a file, extracts the first digit of every number, determines the frequencies of 0-9, and prints out the frequencies (in percentages) of the numbers 0 through 9. I already figured out how to read from my file ("lakes.txt");
FileReader fr = new FileReader ("lakes.txt");
BufferedReader br = new BufferedReader(fr);
//for loop that traverses each line of the file
int count = 0;
for (String s = br.readLine(); s!= null; s = br.readLine()) {
System.out.println(s); //print out every term
count++;
}
String [] nums;
nums = new String[count];
//close and reset file readers
fr.close();
fr = new FileReader ("lakes.txt");
br = new BufferedReader(fr);
//read each line of the file
count = 0;
for (String s = br.readLine(); s!= null; s = br.readLine()) {
nums[count] = s;
count++;
}
I am currently printing out every term just to make sure it is working.
Now I am trying to figure out how to extract the first digit from each term in my string array.
For example, the first number in the array is 15,917, and I want to extract 1. The second number is 8,090 and I want to extract 8.
How can I do this?
To extract the first number from a String
Get the first letter from the String
Parse (1) into a number
For example:
String firstLetter = Character.toString(s.charAt(0));//alternatively use s.substring(0,1)
int value = Integer.parseInt(firstLetter);
This would be placed inside the file reading loop, assuming each line of the file contains a numeric value (in other words, no further processing or error handling of the lines of the file is required).
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TermReader {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader ("lakes.txt");
BufferedReader br = new BufferedReader(fr);
int[] tally = new int[]{0,0,0,0,0,0,0,0,0,0};
int total = 0;
for (String s = br.readLine(); s!= null; s = br.readLine()) {
char[] digits = s.toCharArray();
for(char digit : digits) {
if( Character.isDigit(digit)) {
total++;
tally[Integer.parseInt(Character.toString(digit))]++;
break;
}
}
}
br.close();
for(int index = 0; index < 10; index++) {
double average = tally[index] == 0 ? 0.0 : (((double)tally[index]) / total) * 100;
System.out.println("[" + index + "][" + tally[index] + "][" + total + "][" + Math.round(average * 100.0) / 100.0 + "]");
}
}
}
I need to read a text file, and break the text into blocks of 6 characters (including spaces), pad zeroes to the end of text to meet the requirement.
I tried doing it and here is what I have done.
File file = new File("Sample.txt");
String line;
try {
Scanner sc = new Scanner(file);
while(sc.hasNext()){
line = sc.next();
int chunk = line.length();
int block_size=6;
if((chunk%block_size) != 0)
{
StringBuilder sb = new StringBuilder(line);
int val = chunk%block_size;
for(int i=0; i<val; i++){
sb.append(" ");
}
line = new String(sb.toString());
}
int group = line.length() / block_size;
String[] b = new String[group];
System.out.println(line);
System.out.println(chunk);
int j =0;
for(int i=0; i<group;i++){
b[i] = line.substring(j,j+block_size);
j += block_size;
}
System.out.println("String after spliting is: ");
for(int i=0; i<group;i++){
System.out.println(b[i]);
}
}
}
Now this works fine when the text in the input file has no spaces between words. But when I add spaces gives me a different output. I am stuck up at this point. Any suggestions on the same ?
I don't want to write the solution for you, but I'd advise you that what you're trying to accomplish might be easier to do using a BufferedReader with a FileReader and by using Reader.read(buf) where buf is a char[6];
I want to read a .txt file via a Java program.
Say this is the text file input.txt
abc, test, 1,2,3
abc
abcd
test, 1, 2, 3
Each line represents a row, each comma-separated value represents a column.
Currently my code is:
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
int num = readLines(); //this function just returns the number of lines
for (int i = 0; i < num; i++){
textData[i] = br.readLine();
}
br.close();
This outputs the text file as it was shown above if I print the array. But I require to insert into the array split by comma(could be other character as well, just use comma for now). So this means the output will be such that [abc,test,1,2,3],[abc],[abcd],[test,1,2,3] in the array. How should I proceed?
Thanks for the reply. Update:
Since i got my txt file into a array list,
[abc,test,1,2,3]
[abc]
[abcd]
[test,1,2,3]
How do i find the number of elements in each line?
Create an array list of array lists:
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
int lineCount = readLines();
ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>(lineCount);
for (int i = 0; i < lineCount; i++) {
ArrayList<String> row = new ArrayList<String>();
String line = br.readLine();
for(String s: line.split(",")) {
row.add(s);
}
rows.add(row);
}
br.close();