i have a 3 lines text of int that are data i need to put in some variables, i want to access one by one to all like an array, i can read the firt line but don't know how to go to next line, i know it 's a stupid thing but i'm blocked
public void Load () throws IOException {
BufferedReader in = new BufferedReader(new FileReader("prova.txt"));
String inputLine = in.readLine();
String [] fields = inputLine.split(" "); // Splits at the space
int i=0;
while(inputLine!=null) {
System.out.println(fields[i]); //prints out name
i++;
}
}
i wanto to access to a single int for any line, any tips?
You can get all lines from file using Files.readAllLines() from java8:
List<String> lines = Files.readAllLines(Paths.get("prova.txt"));
for (String line : lines) {
String[] split = line.split(" "));
// use element access by index to do what you want
}
Also if you are familiar with stream api:
Files.lines(Paths.get("prova.txt"))
.flatMap(s -> Arrays.stream(s.split(" ")))
.forEach(System.out::println);
Use the Java NIO API.
Path myPath = Paths.get("prova.txt")
List<String> contents = Files.readAllLines(myPath)
for(String line : contents) {
System.out.println(line);
}
You have to iterate twice : once over the lines in the files (for example using Files.lines(...)) and then over the fields in the line (with say a for loop).
Something like so :
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class Snippet {
public static void main(String[] args) throws IOException {
new Snippet().Load();
}
public void Load() throws IOException {
Files.lines(new File("prova.txt").toPath()).forEach(line -> {
String[] fields = line.split("\\s"); // Splits at the space
for (String field : fields) {
System.out.println(field);
}
System.out.println();
});
}
}
HTH!
What wrong you are doing is that you have read only first line and trying to print all that is there in first line by continuously increasing value of i which will end up with null pointer exception.I have tried the same way you are doing it. Let me know if you have any concern.
public class Snippet {
public static void Load() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("prova.txt"));
String inputLine = in.readLine();
// Splits at the space
while (inputLine != null) {
int i = 0;
String[] fields = inputLine.split(" ");
while (i < fields.length) {
System.out.println(fields[i]); // prints out name
i++;
}
inputLine = in.readLine();
}
}
}
What i am doing here is reading each line splitting it based on space and print everything that came on first line and and then read next line at the end of loop.
Related
I have to do a program and unfortunately I have no idea where to start. It's like we were doing very basic coding and then my teacher went on maternity leave and our substitute thinks we are further along then we actually are. I know how to ready from a file, but I do not know how to put the line into a stack from there.
These are the instructions
1) Read a line and push into a line-stack until the end of file 2) While line_stack is not empty a. Pop one element out and process the following i. Split elements in this line (i.e. numbers) using StringTokenzier ii. Push all numbers into number-stack iii. While number_stack is not empty 1. Pop a number 2. Print a character using that ascii number
If I understand the problem correctly you need to:
Represent a line as a java.lang.String.
Then using java.util.Stack create a Stack< String> and put all the lines there.
Use java.util.StringTokenizer to split each line into multiple parts. Each part will be a String itself.
Turn each part of the line into a number using Integer.valueOf(String)
Put all the numbers into a Stack< Integer>.
Print the right character for each number by casting integer value to char.
I think this may be the solution for your problem:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Stack;
import java.util.StringTokenizer;
public class LinesProcessor {
private static Stack<String> readLinesFromFile(String fileName) throws IOException {
Stack<String> lines = new Stack<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
String line = null;
while ((line = br.readLine()) != null) {
lines.push(line);
}
}
return lines;
}
private static void processNumbers(Stack<Integer> stackOfNumbers) {
while (!stackOfNumbers.empty()) {
Integer number = stackOfNumbers.pop();
System.out.print((char) number.intValue());
}
}
private static void processLine(String line) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
Stack<Integer> stackOfNumbers = new Stack<>();
while (tokenizer.hasMoreTokens()) {
Integer number = Integer.valueOf(tokenizer.nextToken());
stackOfNumbers.push(number);
}
processNumbers(stackOfNumbers);
}
private static void processLines(Stack<String> stackOfLines) {
while (!stackOfLines.empty()) {
String currentLine = stackOfLines.pop();
processLine(currentLine);
}
}
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Name of file missing");
System.exit(1);
}
String fileName = args[0];
Stack<String> stackOfLines = readLinesFromFile(fileName);
processLines(stackOfLines);
}
}
Below is what the text document looks like. The first line is the number of elements that I want the array to contain. The second is the ID for the product, separated by # and the third line is the total price of the products once again separated by #
10
PA/1234#PV/5732#Au/9271#DT/9489#HY/7195#ZR/7413#bT/4674#LR/4992#Xk/8536#kD/9767#
153#25#172#95#235#159#725#629#112#559#
I want to use the following method to pass inputFile to the readProductDataFile method:
public static Product[] readProductDataFile(File inputFile){
// Code here
}
I want to create an array of size 10, or maybe an arrayList. Preferably to be a concatenation of Customer ID and the price, such as Array[1] = PA/1234_153
There you go the full class, does exactly what you want:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.io.IOException;
class myRead{
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader inputFile = new BufferedReader(new FileReader("test.txt"));
String numberOfElements = inputFile.readLine();
//this is the first line which contains the number "10"
//System.out.println(numberOfElements);
String secondLine = inputFile.readLine();
//this is the second line which contains your data, split it using "#" as a delimiter
String[] strArray = secondLine.split("#");
//System.out.println(Arrays.toString(strArray));
//System.out.println(strArray[0]);
String thirdLine = inputFile.readLine();
//this is the third line which contains your data, split it using "#" as a delimiter
String[] dataArray = thirdLine.split("#");
//combine arrays
String[] combinedArray = new String[strArray.length];
for (int i=0;i<strArray.length;i++) {
combinedArray[i]=strArray[i]+"_"+dataArray[i];
System.out.println(combinedArray[i]);
}
}
}
OUTPUT:
PA/1234_153
PV/5732_25
Au/9271_172
DT/9489_95
HY/7195_235
ZR/7413_159
bT/4674_725
LR/4992_629
Xk/8536_112
kD/9767_559
The trick in what I am doing is using a BufferedReader to read the file, readLine to read each of the three lines, split("#"); to split each token using the # as the delimiter and create the arrays, and combinedArray[i]=strArray[i]+"_"+dataArray[i]; to put the elements in a combined array as you want...!
public static Product[] readProductDataFile(File inputFile){
BufferedReader inputFile = new BufferedReader(new FileReader(inputFile));
// the rest of my previous code goes here
EDIT: Everything together with calling a separate method from inside the main, with the file as an input argument!
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
class myRead{
public static void main(String[] args) throws FileNotFoundException, IOException {
File myFile = new File("test.txt");
readProductDataFile(myFile);
}
public static String[] readProductDataFile(File inputFile) throws FileNotFoundException, IOException{
BufferedReader myReader = new BufferedReader(new FileReader("test.txt"));
String numberOfElements = myReader.readLine();
//this is the first line which contains the number "10"
//System.out.println(numberOfElements);
String secondLine = myReader.readLine();
//this is the second line which contains your data, split it using "#" as a delimiter
String[] strArray = secondLine.split("#");
//System.out.println(Arrays.toString(strArray));
//System.out.println(strArray[0]);
String thirdLine = myReader.readLine();
//this is the third line which contains your data, split it using "#" as a delimiter
String[] dataArray = thirdLine.split("#");
//combine arrays
String[] combinedArray = new String[strArray.length];
for (int i=0;i<strArray.length;i++) {
combinedArray[i]=strArray[i]+"_"+dataArray[i];
System.out.println(combinedArray[i]);
}
return combinedArray;
}
}
OUTPUT
PA/1234_153
PV/5732_25
Au/9271_172
DT/9489_95
HY/7195_235
ZR/7413_159
bT/4674_725
LR/4992_629
Xk/8536_112
kD/9767_559
You don't even need the first line. Just read the second line directly into a single string and then split it by using String,split() method.
Read more for split method here.
You could use something like this (Be aware that i can't test it at the moment)
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("fileeditor.txt"));
String read = null;
String firstLine=in.readLine();
//reads the first line
while ((read = in.readLine()) != null) {
// reads all the other lines
read = in.readLine();
String[] splited = read.split("#");
//split the readed row with the "#" character
for (String part : splited) {
System.out.println(part);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
//close file
in.close();
} catch (Exception e) {
}
}
This is how you can do it using Java (don't forget to import):
public static Product[] readProductDataFile(File inputFile){
Scanner s = new Scanner(inputFile);
String data = "";
while(s.hasNext())
data += s.nextLine();
String[] dataArray = data.split("#");
}
You can try this way ..
Reading line by line and storing each row in a array.
Use while storing so it will split and save .
String[] strArray = secondLine.split("#");
Now use the for loop and concat the values as u wish and save ina third array .
For(int i=0 ;i< file.readline;i++)
{
string s = a[customerid];
s.concat(a[productid]);
a[k] =s;
}
Importing a large list of words and I need to create code that will recognize each word in the file. I am using a delimiter to recognize the separation from each word but I am receiving a suppressed error stating that the value of linenumber and delimiter are not used. What do I need to do to get the program to read this file and to separate each word within that file?
public class ASCIIPrime {
public final static String LOC = "C:\\english1.txt";
#SuppressWarnings("null")
public static void main(String[] args) throws IOException {
//import list of words
#SuppressWarnings("resource")
BufferedReader File = new BufferedReader(new FileReader(LOC));
//Create a temporary ArrayList to store data
ArrayList<String> temp = new ArrayList<String>();
//Find number of lines in txt file
String line;
while ((line = File.readLine()) != null)
{
temp.add(line);
}
//Identify each word in file
int lineNumber = 0;
lineNumber++;
String delimiter = "\t";
//assess each character in the word to determine the ascii value
int total = 0;
for (int i=0; i < ((String) line).length(); i++)
{
char c = ((String) line).charAt(i);
total += c;
}
System.out.println ("The total value of " + line + " is " + total);
}
}
This smells like homework, but alright.
Importing a large list of words and I need to create code that will recognize each word in the file. What do I need to do to get the program to read this file and to separate each word within that file?
You need to...
Read the file
Separate the words from what you've read in
... I don't know what you want to do with them after that. I'll just dump them into a big list.
The contents of my main method would be...
BufferedReader File = new BufferedReader(new FileReader(LOC));//LOC is defined as class variable
//Create an ArrayList to store the words
List<String> words = new ArrayList<String>();
String line;
String delimiter = "\t";
while ((line = File.readLine()) != null)//read the file
{
String[] wordsInLine = line.split(delimiter);//separate the words
//delimiter could be a regex here, gotta watch out for that
for(int i=0, isize = wordsInLine.length(); i < isize; i++){
words.add(wordsInLine[i]);//put them in a list
}
}
You can use the split method of the String class
String[] split(String regex)
This will return an array of strings that you can handle directly of transform in to any other collection you might need.
I suggest also to remove the suppresswarning unless you are sure what you are doing. In most cases is better to remove the cause of the warning than supress the warning.
I used this great tutorial from thenewboston when I started off reading files: https://www.youtube.com/watch?v=3RNYUKxAgmw
This video seems perfect for you. It covers how to save file words of data. And just add the string data to the ArrayList. Here's what your code should look like:
import java.io.*;
import java.util.*;
public class ReadFile {
static Scanner x;
static ArrayList<String> temp = new ArrayList<String>();
public static void main(String args[]){
openFile();
readFile();
closeFile();
}
public static void openFile(){
try(
x = new Scanner(new File("yourtextfile.txt");
}catch(Exception e){
System.out.println(e);
}
}
public static void readFile(){
while(x.hasNext()){
temp.add(x.next());
}
}
public void closeFile(){
x.close();
}
}
One thing that is nice with using the java util scanner is that is automatically skips the spaces between words making it easy to use and identify words.
So I need to do exactly what it says in the title, take a text file called "words.txt", have the program read it, take all the words in it, and store them into an array. After that, the program needs to pick one out randomly, and print it in reverse. I'm having a lot of trouble getting it to work, as it always crashes at the end. Here's what I got so far:
import java.io.*;
import java.util.Random;
public class wordReader{
public static void main (String args[]) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("words.txt"));
String strLine;
String[] filearray;
filearray = new String[10];
while ((strLine = br.hasNextLine())) {
for (int j = 0; j < filearray.length; j++){
filearray[j] = br.readLine();
System.out.println(filearray);
}
}
}
}
Alright, this i what I have at the moment:
import java.io.*;
import java.util.Random;
public class wordReader{
public static void main (String args[]) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("words.txt"));
String strLine;
String[] filearray;
filearray = new String[10];
int j = 0;
int i = 0;
Random r = new Random();
while(((strLine = br.readLine()) !=null) && j < filearray.length){
filearray[j++] = strLine;
int idx = r.nextInt(filearray.length);
}
}
}
You can do this easily using the new Files API and StringBuilder to reverse your String. It will cut down your lines of code significantly.
public static void main(String[] args) throws Exception {
Path path = Paths.get("words.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
String[] words = content.split(",|\.|\s+");
int randomIndex = new Random().nextInt(words.length);
String word = words[randomIndex];
String reversed = StringBuilder(word).reverse().toString();
System.out.println(reversed);
}
Try using the StringTokenizer to read the line.
http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Lot's of ways to accomplish this. Here's a recursive method that prints as the calls are popping off the return stack. This was adapted from Reversing Lines With Recursion Java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
public class ReverseLines {
public static BufferedReader input;
public static PrintWriter output;
public static void main(String[] args) throws Exception {
input = new BufferedReader(new FileReader("/tmp/words.txt"));
output = new PrintWriter(System.out);
reverse(input, output);
input.close();
output.flush();
output.close();
}
public static void reverse(BufferedReader input, PrintWriter output)
throws Exception {
String line = input.readLine();
if (line != null) {
reverse(input, output);
output.println(line);
}
}
}
You don't seem to have gotten to the point of doing the random index selection or the line reversal yet, so I won't address that stuff here. There are endless duplicates all over StackOverflow to tell you how to reverse a String.
At the moment, you're getting compile errors because (among other things) you're trying to use a method (BufferedReader#hasNextLine()) that doesn't exist. It looks like you were mixing up a couple of other approaches that you might have found, e.g.:
int j = 0;
while ((strLine = br.readLine()) != null) { // Set strLine to the next line
filearray[j++] = strLine; // Add strLine to the array
// I don't recommend printing the whole array on every pass through the loop...
}
You'll notice that I also took out your inner for loop, because it was just setting every element of your list to the most recent line on every iteration. I'm assuming you wanted to populate the list with all of your lines. Realistically, you should also check whether j is in an acceptable range as well:
while (((strLine = br.readLine()) != null) && j < filearray.length) {...}
Note that realistically, you'd almost certainly be better off using a List to store your lines, so you could just add all the lines to the List and not worry about the length:
List<String> contents = new ArrayList<String>();
while ((strLine = br.readLine()) != null) {
contents.add(strLine); // Add strLine to the List
}
But, this does smell like homework, so maybe you're required to use a String[] for whatever reason.
Finally, there's a discrepancy between what you've written in your question and what your program looks like it's intended to do. You claim that you need a list of each word, but it looks more like you're trying to create a list of each line. If you need words instead of lines, you'll need to split up each line and add each token to the list.
I'm trying to read a line of text from a text file and put each line into a Map so that I can delete duplicate words (e.g. test test) and print out the lines without the duplicate words. I must be doing something wrong though because I basically get just one line as my key, vs each line being read one at a time. Any thoughts? Thanks.
public DeleteDup(File f) throws IOException {
line = new HashMap<String, Integer>();
try {
BufferedReader in = new BufferedReader(new FileReader(f));
Integer lineCount = 0;
for (String s = null; (s = in.readLine()) != null;) {
line.put(s, lineCount);
lineCount++;
System.out.println("s: " + s);
}
}
catch(IOException e) {
e.printStackTrace();
}
this.deleteDuplicates(line);
}
private Map<String, Integer> line;
To be honest, your question isn't particularly clear - it's not obvious why you've got the lineCount, or what deleteDuplicates will do, or why you've named the line variable that way when it's not actually a line - it's a map from lines to the last line number on which that line appeared.
Unless you need the line numbers, I'd use a Set<String> instead.
However, all that aside, if you look at the keySet of line afterwards, it will be all the lines. That's assuming that the text file is genuinely in the default encoding for your system (which is what FileReader uses, unfortunately - I generally use InputStreamReader and specify the encoding explicitly).
If you could give us a short but complete program, the text file you're using as input, the expected output and the actual output, that would be helpful.
What I understood from your question is to print the lines which do not have duplicate words in the line.
May be you could try the following snippet for it.
public void deleteDup(File f)
{
try
{
BufferedReader in = new BufferedReader(new FileReader(f));
Integer wordCount = 0;
boolean isDuplicate = false;
String [] arr = null;
for (String line = null; (line = in.readLine()) != null;)
{
isDuplicate = false;
wordCount = 0;
wordMap.clear();
arr = line.split("\\s+");
for(String word : arr)
{
wordCount = wordMap.get(word);
if(null == wordCount)
{
wordCount = 1;
}
else
{
wordCount++;
isDuplicate = true;
break;
}
wordMap.put(word, wordCount);
}
if(!isDuplicate)
{
lines.add(line);
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
private Map<String, Integer> wordMap = new HashMap<String, Integer>();
private List<String> lines = new ArrayList<String>();
In this snippet, lines will contain the lines which do not have duplicate words in it.
It would have been easier to find your problem if we knew what
this.deleteDuplicates(line);
tries to do. Maybe it is not clearing any of the data structure used. Hence, the words checked in previous lines will be checked for other lines too though they are not present.
Your question is not very clear.
But while going through your code snippet, I think you tried to remove duplicate words in each line.
Following code snippet might be helpful.
public class StackOverflow {
public static void main(String[] args) throws IOException {
List<Set<String>> unique = new ArrayList<Set<String>>();
BufferedReader reader = new BufferedReader(
new FileReader("C:\\temp\\testfile.txt"));
String line =null;
while((line = reader.readLine()) != null){
String[] stringArr = line.split("\\s+");
Set<String> strSet = new HashSet<String>();
for(String tmpStr : stringArr){
strSet.add(tmpStr);
}
unique.add(strSet);
}
}
}
Only problem with your code I see is That DeleteDup doesn't have return type specified.
Otherwise code looks fine and reads from file properly.
Please post deleteDuplicates method code and file used.
You are printing out every line read, not just the unique lines.
Your deleteDuplicateLines() method won't do anything, as there will never be any duplicates in the HashMap.
So it isn't at all clear what your actual problem is.