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 8 years ago.
Improve this question
New to java. I want to read in a file that has lines formatted like this
en Fox 3 1344
en Bird 19 144
en Dog 93 1234
For each line I want to pick the contents of column 2 and 3. In the case of the first line "Fox" and "3". and display them. So far this is what I have.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class pagecounts {
public static void main(String[] args) throws FileNotFoundException {
String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
*// letter in column 2 and 3 pick code goes here.*
System.out.println(content);
}
}
Any help will be appreciated.
Assuming that each column can contain only one value (word/number) you can use Scanner to read all tokens form one line and use only these which interest you.
try(Scanner sc = new Scanner(new File(path))){//try-with-resources
//will automatically close stream to file
while (sc.hasNext()){
String col1 = sc.next();
String col2 = sc.next();
int col3 = sc.nextInt();//you can also use next() if you want to get this token as String
int col4 = sc.nextInt();//same here
System.out.printf("%-15s %d%n", col2, col3);
}
}
You can also read file line by line and split each line on space
try(Scanner sc = new Scanner(new File(path))){//try-with-resources
//will automatically close stream to file
while (sc.hasNextLine()){
String line = sc.nextLine();
String[] tokens = line.split("\\s+");//I assume there are no empty collumns
System.out.printf("%-15s %s%n",tokens[1],tokens[2]);
}
}
You can also treat this file as CSV file (Comma Separated Values) where values are separated with space. To parse such file you can use library like OpenCSV with separator defined as space
try(CSVReader reader = new CSVReader(new FileReader(path),' ')){
String[] tokens = null; // ^--- use space ' ' as delimiter
while((tokens = reader.readNext())!=null)
System.out.printf("%-15s %s%n",tokens[1],tokens[2]);
} catch (IOException e) {
e.printStackTrace();
}
Use split:
System.out.println(content.split(" ")[1] + " " + content.split(" ")[2]);
Related
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 2 years ago.
Improve this question
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Process_TCPProbe_dm{
public static void main(String[] args) throws IOException {
//Extracting the port numbers from the file names passed in the arguments
String portNumber1 = args[1].substring(9, 14);
String portNumber2 = args[2].substring(9, 14);
String portNumber3 = args[3].substring(9, 14);
int i = 0;
Scanner s = new Scanner(new FileReader(args[0]));
//Initialising array of contents with length equals to number of lines in the input file
String[] contents = new String[18];
while(true)
{
if (i == 18)
break;//Skipping the last line of the file
//Replaces the whitespace with comma and stores in the string array
contents[i] = s.nextLine().replace(" ", ",");
i++;
}
BufferedWriter bw1 = new BufferedWriter(new FileWriter(args[1]));
BufferedWriter bw2 = new BufferedWriter(new FileWriter(args[2]));
BufferedWriter bw3 = new BufferedWriter(new FileWriter(args[3]));
//Iterating the array of contents using a for each loop
for(String each:contents)
{
//Writing the string to the corresponding file which matches with the portNumber
//along with a new line
if (each.contains(portNumber1))
{
bw1.write(each);
bw1.newLine();
}
else if(each.contains(portNumber2))
{
bw2.write(each);
bw2.newLine();
}
else if(each.contains(portNumber3))
{
bw3.write(each);
bw3.newLine();
}
}
//This is necessary to finally output the text from the buffer to the corresponding file
bw1.flush();
bw2.flush();
bw3.flush();
//Closing all the file reading and writing handles
bw1.close();
bw2.close();
bw3.close();
s.close();
}
}
Here is my code, however, it only reads a file the size of 19 lines. I know i could use an ArrayList, but I'm not exactly sure how to go about it. I hope my question makes sense. If it'll help you understand better ill put the purpose of the code below.
This image is of the instructions for what the code is written for. It might just be extra information, but I put it here in case it'll better help to explain my question.
Just replace your array with Array Lins like this ArrayList<String> list = new List<>(); and then replace contents[i] = s.nextLine().replace(" ", ",");with list.add(s.nextLine().replace(" ", ","));. After this you will not need counter "i" anymore and break you loop in if condition. Just add scanner.hasNext() in a while condition.
Your looping condition should be based on Scanner.hasNextLine and you don't need the variable i. Use an ArrayList to score an unknown amount of elements.
Scanner s = new Scanner(new FileReader(args[0]));
final List<String> contents = new ArrayList<>();
while(s.hasNextLine()){
contents.add(s.nextLine().replace(" ", ","));
}
This can be shortened using Files.lines. Note that this throws an IOException that you will need to handle.
final List<String> contents = Files.lines(Paths.get(args[0]))
.map(s->s.replace(" ", ",")).collect(Collectors.toList());
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 3 years ago.
Improve this question
I am trying to print Ben, Adam, John and Smith into a txt file with the names on separate lines. I am partly successful, however I keep getting FileNotFoundException at the end after the code runs. Why is that?
"Ben Adam John Smith" passes through String names
File Writing code:
public String writeYourName(String names) throws Exception {
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("names.txt")));
for(int i = 0; i < 1; i++) {
output.write(names);
}
output.close();
Scanner scan1 = new Scanner(new File("names.txt"));
while(scan1.hasNext()) {
if(scan1.hasNext()) {
System.out.println(scan1.next());
}
}
return names;
}
Test file for FileWriting:
FileWriting fileWriting = new FileWriting();
FileReading fileReading = new FileReading();
fileWriting.writeYourName("Ben Adam John Smith");
System.out.println(fileReading.readName1(fileWriting.writeYourName("Fred")));
Code that the error points to:
public class FileReading {
public String readName1(String nameFile) throws Exception {
-> Scanner scan = new Scanner(new File(nameFile)); <-
String name = scan.next();
String nextLine = "";
while(scan.hasNextLine()) {
nextLine = scan.nextLine();
}
return name + " " + nextLine;
}
Test file for FileReading:
System.out.println(fileInput.readName1("namefile.txt"));
You are trying to read a file where the filename consists of a name or names here:
fileReading.readName1(fileWriting.writeYourName("Fred"))
as writeYourName doesn't return a file name but a string of names of persons (or in this case, one name, of one person: Fred):
return names;
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 6 years ago.
Improve this question
I need to write a progam to read a text file and compare its lines. I want to store them in an array, but I do not how to do this and how to compare, if they are equal.
package pantoum;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Pantoum {
public static void main(String[] args) throws FileNotFoundException {
//get filename input from user
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the full file name: ");
String fileName = keyboard.nextLine();
File inputFile = new File(fileName);
if (inputFile.exists()){
//create scanner to read file
Scanner input = new Scanner(inputFile);
//while (input.hasNext());{
String title = input.next();
System.out.println(title);
}
else
{
System.out.println("Sorry, that file does not exist.");
}
}
}
i personally prefer to use buffered reader when it comes to reading from a text file.
boolean equal=false;
String lines[] =new [10];
// or however long the array needs to be.
int count=0;
BufferedReader infile = new BufferedReader(new FileReader("<Name of file>"));
do {
lines[count] = infile.readLine();
count++;
} while (lines[count] != null);
for(int i=0;i<lines.length();i++) {
for(int j = i+1; j<lines.length()-1;j++){
if(lines[i].equals(lines[j])){
equal=true;
system.out.print(lines[i]+" and "+lines[j]+" are equal");
}}}
if(!equal){
system.out.print("Sorry your text did not equal any text from the text file");
}
i hope this helped and i hope i have explained everything well enough for you to understand, if not feel free to ask.
I personally would read each line into a String[] position and then in a loop check if String[i].equals(String[j]). If you need a rough idea how to code this let me know.
You can just use scanner's nextLine() method to get an entire line and then compare them using String.equals()
something like
String line1 = input.nextLine();
String line2 = input.nextLine();
if(line1.equals(line2){
doStuff();
}
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 am currently learning how to use Java. I am trying to read a file using the scanner class and I want to read the file but ignore the rest of the line after a certain character eg #. say the file reads
P5 #ignorethis
#ignorealso
123 123 123 #thisneedstogo
355 255 345 #alsothis goes
the file I am trying to read has comments after the symbol '#' and they last till the end of the line. I want to read the strings of the file, whilst ignoring '#' and everything after that.
Any help would be much appreciated, thanks :)
Read the file one line at a time and then consider using the replaceAll(String string) method which takes a regular expression on the line you have just read. You would then use something like so: #.*$ to replace the # character and whatever follows till the end of the string with an empty string.
You could then write the string back to some other file or console once that you are done.
From the Scanner's class doc:
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace.
You can do it using useDelimiter method and regular expressions
As an example:
public static void main(String[] args) {
String s = " P5 #ignorethis\n" +
" #ignorealso\n" +
" 123 123 123 #thisneedstogo\n" +
" 355 255 345 #alsothis goes";
Scanner scanner = new Scanner(s).useDelimiter("#.*");
while (scanner.hasNext()){
System.out.print(scanner.next());
}
}
You can write something like this:
Scanner scanner = new Scanner(new FileInputStream(new File("input.txt")));
while(scanner.hasNextLine()){
String str = scanner.nextLine();
System.out.println(str.substring(0, str.indexOf("#")));
}
scanner.close;
Hope this helps.
You can also read whole line, and then use just one part of it, like this:
public void readFile(File file){
String line = "";
try{
scanner = new Scanner(file);
}catch (FileNotFoundException ex){
ex.printStackTrace();
System.out.println("File not found");
}
while (scanner.hasNext()){
line = scanner.nextLine();
String parts[] = line.split("#");
System.out.println(parts[0]);
}
}
This method read new line to String, split a String in a place of "#", and use part before "#" occurrence. Here is output:
P5
123 123 123
355 255 345
BufferedReader br = new BufferedReader(new FileReader("name_file"))) {
String line;
String result = "";
while ((line = br.readLine()) != null) {
if(line.trim().startsWith("#"))
{
System.out.println("next line");
}
else
{
int index = line.indexOf("#");
if(index != -1){
String split = line.substring(0,index);
String[] sLine = line.trim().split("\t");
result = result + " " +split;
}
else
{
String[] sLine = line.trim().split("\t");
result = result + " " +line;
}
}
}
br.close();
System.out.println(result);
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 have this method which receive as parameters pdfText(which is a String containing text from a pdf file after parsing) and fileName which is the file where i want to write that text
But now I need to find the word "Keywords" in this text and extract only the words after it,which are in the same line(until the newline character).
For example I have one text which contains somewhere the following line
Title:Something.
"Keywords : Computers, Robots, Course"
Tags:tag1,tag2,tag3.
And the result should be the following list ["Computers","Robots", "Course"].
Solved Question
So I've searched how to solve my question..here is a solution,not very smart but it works:
//index of first appearence of the word
int index = pdfText.indexOf("Keywords");
//string from that to the end
String subStr = pdfText.substring(index);
//index of first appearence of the new line in the new string
int index1 = subStr.indexOf("\n");
//the string we need
String theString = subStr.substring(9,index1);
System.out.println(theString);
//write in the file..use true as parameter for appending text,not overwrite it
FileWriter pw = new FileWriter(fileName,true);
pw.write(theString);
pw.close();
Honestly, this question is too situation specific. Regardless :)
Writing to file
String pdfText = "pdfText";
String fileLocation = "fileLocation";
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileLocation), "utf-8"));
writer.write(pdfText); // String you want to write (i.e. pdfText)
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {writer.close();} catch (Exception ex) { ex.printStackTrace(); }
}
It's always a good idea to specify the encoding type. ("utf-8"). It might not matter for your assignment though. You might also need to append to the file, and not re-write it completely, in which case, you should use a different constructor for the FileOutputStream, new FileOutputStream(getFileLocation(), true) . As for the many try/catch blocks, don't follow my example. It's how I manage to close my resource, as eclipse recommends haha.
Parsing the String
If you have a line such as "Keywords : Computers, Robots, Course",
String str = "Keywords : Computers, Robots, Course";
String[] array = str.substring(indexOf(':') + 1).split(",");
//this array = ["Computers", "Robots", "Course"]
Now you have an array which you can loop through and write/print out however you'd like.
You could use regex to extract the words after the word "Keyword:" like this :
String regex = ".*Keywords\\s*:(.*)\\n.*";
String extractedLine = yourText.replaceAll( regex, "$1" );
System.out.println( extractedLine );