Read input from text file in java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to read input from a text file in java. I have a text file as follows.
5
4
abcd
6
8
defgh
10
I want to read each character from file as a separate entity and work on that character individually like storing 4 in database separating abcd as a b c d and work on them individually.
What are the various ways to do it. What is the most efficient way.

The easy way (and short) if you use Java 7:
List<String> lines = Files.readAllLines(Paths.get("path to file"), StandardCharsets.UTF_8);
It will put all file data to list where list item represents one row

Use read line if your file has new lines.
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}

If you want to use each character individually, then using a Scanner might be the way to go:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class SOExample {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("myfile.txt"));
sc.useDelimiter("");
while (sc.hasNext()) {
String s = sc.next();
if (s.trim().isEmpty()) {
continue;
}
System.out.println(s);
}
sc.close();
}
}
output:
5
4
a
b
c
d
6
8
d
e
f
g
h
1
0

Related

How would you add all the numbers inside a single element of an array? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
How would you go about adding the total number to all the integers inside an array element?
My code below is what I have and the issue is the multiple numbers are all displayed in different rows but I can't get them to add together because its all considered one integer.
This is what my output looks like.
462085
361250
351477
328955
But when I attempt to alter the numbers in any way I get something like this,
+2
462087
361252
351479
328957
When I really want to get just get the total sum of the numbers.
Desrired Output:
1503767
I attempted to use .parseInt() but that did not seem to make a difference.
import java.io.*;
import java.nio.charset.StandardCharsets;
public class babySort {
public static void main(String[] args) {
File inputFile = new File("src/babynames.txt");
try (BufferedReader br = new BufferedReader(new FileReader(inputFile, StandardCharsets.UTF_8))) {
String input;
String maleNames;
while ((input = br.readLine()) != null) {
// process the line
String[] inputSplit = input.split("\\s+");
// System.out.println(inputSplit[2]);
int maleBb = Integer.parseInt(inputSplit[2]);
System.out.println(maleBb);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
You want the total. Declare a variable to compute the total with before your loop. Add the values to the total. Print it after your loop. Like,
int total = 0;
while ((input = br.readLine()) != null) {
String[] inputSplit = input.split("\\s+");
// int maleBb = Integer.parseInt(inputSplit[2]); // what is a maleBb?
total += Integer.parseInt(inputSplit[2]);
}
System.out.println(total);

check two different files in java and compare them [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have two file .First the property file and second the content file
first file
properties
{
"rowcount" : "3"
"delim" : "|"
}
second file
a|b|c
d|e|f
g|h|i
i want to read both the file and check whether the second file follows the rule .(the structure of the first file will always be similar )
Well, first of all i think the first file should be a properties.json with this syntax:
{
properties: {
rowcount: "3",
delim: "|"
}
}
With a JSONParser you can read the JSON file and map it in a Object.
Then with a FileReader you can deal with the second file. For the validation part i think that a regular expression and a rowcount from the FileReader can easily solve the problem.
For the first part, simply read in the rowcount number from the first file and compare to the line count from the second file.
For the second part, read in delim and then use a Scanner or similar to read the second file using delim as your delimiter. If you only want a single character in between each delimiter, then test for this as you read the file, and throw an exception if you see more than a single character being read in.
From the example link:
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]) throws IOException {
char[] chars = new char[100]; //If you know how many you want to read
//(if not, use an ArrayList or similar)
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
// Set delimiters to newline and pipe ("|")
//Use newline character OR (bitwise OR is "|") pipe "|" character
//since pipe is also OR (thus a meta character), you must escape it (double backslash)
src.useDelimiter(src.useDelimiter(System.getProperty("line.separator")+"|\\|");
// Read chars
for(int i = 0; src.hasNext(); i++) {
String temp = src.next();
if(temp.length != 1)
System.out.println("Error, non char"); //Deal with as you see fit
chars[i] = temp.charAt(0); //Get first (and only) character of temp
}
fin.close();
//At this point, chars should hold all your data
}
}

How to make Scanner read more than one line? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Improve this question
I have a text corpus, which I have to read, split, sort and perform other operations on it.
In the very beginning, when I split it, I see that the Scanner only reads one line. This is the code:
public class CorpusTest {
public static void processCorpus(Scanner scanner) throws IOException{
String line="0";
while (scanner.hasNextLine()) {
line = scanner.nextLine();
}
String[] w = line.replaceAll("[^a-zA-Z\\s]","").toLowerCase().split(" ");
for (int i = 0; i < w.length; i++) {
w[i].trim();
}
System.out.println("Word" + "\t" + "Frequency");
System.out.println(Arrays.toString(w));
}
public static void main(String [] args) throws IOException{
File temp = new File("input.txt");
Scanner scanner = new Scanner(temp);
CorpusTest.processCorpus(scanner);
}
}
I tried adding:
String text = new Scanner( new File("input.txt") ).useDelimiter("\\A").next();
But I get errors because in the method above I am working with an array.
The while loop only reads the last line, which is no good.
I'm not sure what your issue is, and it seems as if you might be trying to make things more difficult than they need to be. Why not simply read your lines in with the Scanner, one at a time, put them into a StringBuilder, and then when the text has been read in, convert to a String and manipulate your String to your hearts content?
#user2864740 helped me out with redirecting me to the right source. I used this instead of the loop in the beginning of my code:
String content = new Scanner(new File("input.txt")).useDelimiter("\\Z").next();
String[] w = content.replaceAll("[^a-zA-Z\\s]","").replaceAll("\n","").toLowerCase().split(" ");
Now it works.

Read first 100 string array, java i/o [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I was directed from to this website from a friend. The goal is to read the first 100 strings in the txt file and count how many times those words appear and print them off.
Thank you so much in advance. I've done very well with code but this has stumped me for some reason.
import java.util.Arrays;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Program6 {
public static void main(String[] args) throws FileNotFoundException {
WordAnalysis a = new WordAnalysis();
a.ReadFile();
}}
class WordAnalysis{
String[] coun = new String[1000];
int[] ana = new int[100];
void ReadFile() throws FileNotFoundException {
Scanner read = new Scanner(new File("myths.txt"));
int[] ana = new int[100];
String coun = new String();
String word=null;
while(read.hasNext()) {
word = read.next();
String[] arrWord = word.split(" ");
}
}
}
Procedure:
1: Read lines [0,99] via nextLine() from Scanner
2: Split up line with another Scanner and use next() to get each word. Alternatively, you can use split.
3: Put each word in a HashMap(String, Integer) where String is the word, and Integer is the number of times it has appeared
4: Iterate through HashMap and prints out key, value pairs
Check this, here I've used a map to keep word count.
int count = 0;
HashMap<String, Integer> wordCntMap = new HashMap();
while (read.hasNext()) {
count++;
word = read.next();
String[] arrWord = word.split(" ");
if (count == 100) {
break;
}
for (String str : arrWord) {
Integer num = wordCntMap.get(str);
if (num == null) {
wordCntMap.put(str, new Integer(1));
} else {
wordCntMap.put(str, num + 1);
}
}
}
System.out.println("Word Count " + wordCntMap);
Welcome to Stack Overflow, where no answer is too stupid and no comment too thoughtless.
It seems fairly clear however that you haven't finished writing this code. :-)
Now that you have your words in arrWord, you need to start using some sort of structure that will allow you to keep track of each word and how many times its been seen.
There are plenty of containers that let you use a string as a key and an integer as a value. For your purposes it doesn't matter which one you use.
For each word in arrWord, see if you can find it in your structure (Dictionary, Hashmap, whatever). If you can't find 'word', insert a new entry of [word, 1]. If you can find 'word' then increment the counter that you find.
When you are done, all you need to do is print out the key-value pair for each entry in your structure.
HTH!

Java 1.4.2 - Class Variables [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a simple program in progress that needs the declaration lines
read = new BufferedReader(new FileReader("marks.txt"));
and
line = read.readLine();
to be class variables. How would I do this?
Here is the code I wrote so far.
import java.io.*;
import java.math.*;
public class WriteKong
{
public static String line;
public static BufferedReader read;
public static PrintWriter write;
public static void main(String[] args) throws IOException
{
read = new BufferedReader(new FileReader("marks.txt"));
line = read.readLine();
while(line != null)
{
System.out.println(line);
read.readLine();
}
}
public static void sort()
{
// THIS IS WHAT THE FUNCTION DOES:
// > check the fourth digit in the line
// > if there is no fourth digit then store the mark
// > if mark is less than 50 then write to "fail.txt"
// > if mark is 50 or greater then write to "pass.txt"
}
}
EDIT: I want these variables to be declared as a class variable. I don't want to go through the pain of redefining the same variables in all of the methods I use.
They are class variables in your code. The code satisfies the requirements given.
If you're confused why your loop does not read all the lines from the file it's because you never assign the newly read line to to line.

Categories

Resources