How to set variable equal to text in word document [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to create a Java String from the contents of a file
How to set a java string variable equal to “htp://website htp://website ”
I am making aprogram because I have about 50 pages of a word document that is filled with both emails and other text. I want to filter out just the emails. I wrote the program to do this which was very simple, not I just need to figure away to store the pages in a string variable.
I have a text file imported into my code File f=new File("test.txt"); Now I just need to find a way to save the text in this file into a String variable. Any help?

Okay, so based on your edit you're working with a text file and not a word file (two very different things ;) )
This is pretty simple, you just use a scanner class as such:
File file = new File("data.txt");
String s = new String();
try{
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
s += sc.nextLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Now bear in mind, if you just want a single line at a time from your text file (I have no idea what it is you're looking for, or what the data looks like) it's more likely that you'd want to store your data as an array of Strings or a linked list

Related

Splitting a text file

I have this text file of the format:
Token:A1
sometext
Token:A2
sometext
Token:A3
I want to split this file into multiple files, such that
File 1 contains
A1
sometext
File 2 contains
A2
sometext
I do not have much idea about any programming or scripting language as such, what would be the best way to go about the process? I was thinking of using Java to solve the problem.
if you want to use java, I would look into using Scanner in conjunction with File and PrintWriter with a for loop and some exception handling you will be good to go.
import the proper libraries!
import java.io.*;
import java.util.*;
declare the class of course
public class someClass{
public static void main(String [] args){
now here's where stuff starts to get interesting. We use the class File to create a new file that has the name of the file to be read passed as a parameter. You can put whatever you want there whether its a path to the file or just the file name if its in the same directory as your code.
File currentFile = new File("new.txt");
if (currentFile.exists() && currentFile.canRead()){
try{
next we create a scanner to scan through that newly created File object. the for loop continues on as long as the file has new tokens to scan through. .hasNext() returns true only if the input in the scanner has another token. PrintWriter writes and creates the files. I have it set that it will create the files based on the iteration of the loop (0,1,2,3 etc) but that can be easily changed. (see new PrintWriter(i + ".txt". UTF-8); )
Scanner textContents = new Scanner(currentFile);
for(int i = 0; textContents.hasNext(); i++){
PrintWriter writer = new PrintWriter(i + ".txt", "UTF-8");
writer.println(textContents.next());
writer.close();
}
these catch statements are super important! Your code wont even compile without them. If there is an error they will make sure your code doesn't crash. I left the inside of them empty so you can do what you see fit.
} catch (FileNotFoundException e) {
// do something
}
catch (UnsupportedEncodingException i){
//do something
}
}
}
}
and thats pretty much it! if you have any questions be sure to comment!
There is no best way and it depends on your environment and need actually. But for any language figure out your basic algorithm and try using the best available data structure(s). If you are using Java, consider using guava splitter and do look into its implementation.

i want to display these two values in a text file [duplicate]

This question already has answers here:
How do I save a String to a text file using Java?
(24 answers)
Closed 6 years ago.
I have two string variables containing some user input.
String name="neil";
String mobile="5555";
now I want to display neil an 5555 in a text file. Please help me to display this in a text file, I know how to display content of a file which is already exist, but donot know how to work with this case, please help me...
PrintWriter out = response.getWriter();
This should be changed to use "java.io.File" class.
Has been explained in this thread: How to use PrintWriter and File classes in Java?
File file = new File("C:/Users/Me/Desktop/directory/file.txt");
file.getParentFile().mkdirs();
PrintWriter out = new PrintWriter(file);
Something like this.
ps: check out "try-with-resources"

Java .dat operations Excercise [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
Today is my first day at Java, i'm really new at this, have been solving some problems, but I'm stucked. I know it's really simple but I hope you can help me. Thanks!
I want to identify if an Apple is a Green or Red.
These are the requirements:
All Apples will be listed in the following file: apples.dat
We must divide the results in Red or Green
Villains are those Super-Powered people whose names contain a "A".
Green Apples must be saved in a file called green.dat
Red Apples must be saved in a file called red.dat
So my 2 main concerns, is how to operate with .dat files, and secondly, how to treat the fact that the condition to identify one or another may vary in a future.
Thanks in advance!
To open a file in java, it is easy. You need to do the following:
Create File object referencing the file
Create BufferedReader and pass it FileReader object to which pass File object
Use the BufferedReader's readLine() method to read line by line in while loop with condition while (line != null)
Process the line that has been read.
Wrap above in try/catch block
See below sample code, that read apples.dat file and print out all those who are reds and greens as well as output greens and reds in greens.dat and reds.dat repectively.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
public class ReadFileJava {
public static void main(String[] args) {
//list that stores all greens
ArrayList<String> greens = new ArrayList<String>();
//list that stores all reds
ArrayList<String> reds = new ArrayList<String>();
//file that references the file containing all green and red apples
File file = new File("C:\\test_java\\apples.dat");
//try and catch block in case file not found or any other I/O error
try {
//open the file
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
//keep reading line by line, if end of file then line == null
while ((line = br.readLine()) != null) {
//if line contains "d" then Green it is and add it
//to the list of reds
if(line.indexOf("d") != -1) {
System.out.println("Green found!");
greens.add(line);
} else {
//add it to the list of superheors.
System.out.println("Red found.");
reds.add(line);
}
}
//close the reading file resource
br.close();
//file to print greens back
File greensFile = new File("C:\\test_java\\greens.dat");
//file to print reds
File redsFile = new File("C:\\test_java\\reds.dat");
//PrintStream takes care of open stream to files above
//and writing line by line, first write greens
PrintStream output = new PrintStream(redsFile);
//loop through list of previously created greens
for(int i = 0; i < greens.size(); i++) {
//write hered to file
output.println(reds.get(i));
}
//redirect the print stream to greens file
output = new PrintStream(greensFile);
//loop through list of greens
for(int i = 0; i < greens.size(); i++) {
//add green to the file
output.println(greens.get(i));
}
//close the output stream
output.close();
} catch (IOException e) {
//if file not found, or any other I/O error, then error
//so check the location of file
e.printStackTrace();
}
}
}
Separated file for greens.dat and reds.dat are created in the locations specified (please change the location from C:\\test_java\\filename.extension to wherever your files are located).
Welcome to Java.
Java covers a LOT of topics so, it doesn't hurt (much) to ask for some advice on getting started.
Some basic things you will need to know before getting started:
basic things #1) Editing files: you'll need to be able to edit files.
Some files will hold your Java programs.
Other files will hold your data (like a list of names).
basic things #2) Running a Java program: Verify you understand how to make HelloWorld run.
search google for: java hello world step by step
basic things #3) If-statements:
search google for: java introduction to if statemetns
basic #4) Strings: you'll need to know how to define and work with Strings.
search google for: java introduction to strings
Now we can start by breaking down what you need to do.
step 1) Figure out how to work with names.
Hint: you'll want use java's String type to hold names.
step 2) Find out if a name includes the letter "D".
Hint: search google for: java how to find out if a character is in a string
step 3) Read names from a file.
Hint: search google for: java how to read a string from a file line by line
step 4) Write a name to a file (specific file depends on #1).
Hint: search google for: java how to write to a file line by line
hint: you will want to open two files for output, one for Heroes and and one for Villains.
hint: don't use the same file name to read from and write to; make up different file names for writing to.
Good luck to you, being at the very bottom of a learning curve can be an uncomfortable place to be.
Keep working at it.
closing hint: Google is your friend (I hope the above examples are a little bit helpful, sometimes when you're just starting out it can be hard to know what to search for).

Checking for duplicate string in file java

I have an file, where I am writing data to it. I've tried googling, but all examples I have tried have just confused me more.
I am inputting data into a file, and this is happening correctly, where the items selected are being appended to the file. Where my issue is, is that I want to check whether the string being inputted already exists in the file, and if it does, I want to skip it.
The code I am using to input the data to the file is below, but I am not sure how to change it to check for a duplicate.
for (EventsObj p : boxAdapter.getBox()) {
if (p.box){
String result = p.name + " " + p.price;
try {
// open file for writing
OutputStreamWriter out= new OutputStreamWriter(openFileOutput("UserEvents.txt",MODE_APPEND));
// write the contents to the file
out.write(result);
out.write('\n');
// close the file
out.close();
}
catch (java.io.IOException e) {
//do something if an IOException occurs.
Toast.makeText(this, "Sorry Text could't be added", Toast.LENGTH_LONG).show();
}
}
}
It is getting the checkboxes ticked, then getting the name and price related to it and appending it to file. But I want to carry out a check that this does not already exist. Any help would be appreciated and I've exhausted google and tried many things.
So, if I understood your question correctly the file contains a number of strings delimited by newline.
What you want to do is to read the file contents line by line, and store the lines in a HashSet<String>. Then, you open the file for appending and append the additional string, but only if the file did not contain the string already. As the other answer suggested, you use the contains method. However, unlike the other answer I'm not suggesting to use a list of strings; instead, I'm suggesting the use of a HashSet as it's more efficient.
While reading the file contents line by line, you can perform some basic checks: does the file already contain duplicate rows? You may want to handle those by giving the user a warning that the file format is invalid. Or you may want to proceed nevertheless.
You should firstly read from the file and create a list of strings with all your inputs.
Then before adding to the file you can check if the list of strings contains the string you want to add (just make sure that the strings share the same format such that a match will be found). If it returns false add to the file, if yes don't add to the file.
Shouldn't be such a tremendous task. You can make use of the contains method.
You might need to keep the contents of the file in a String in your program. A little inefficient, but at the moment I do not see any other way but to keep track of things in your program instead of on the file.
So before you run the program which appends text to the file, the very first thing you should probably do is parse the file for all text:
File yourFile = new File("file-path-goes-here");
Scanner input = null;
try {
input = new Scanner (new FileInputStream(yourFile) );
}
catch (FileNotFoundException e) {;;;}
String textFromFile = "";
while (input.hasNextLine())
textFromFile += input.nextLine() + "\n";
//Now before adding to the file simply run something like this
if(textFromFile.indexOf("string-to-write-to-file") != -1)
;//do not write to file
else {
;//write to file and add to textFromFile
textFromFile += "string-you-added-to-file" + "\n";
}
Hope this answers your question. Let me know if something is not clear.

Best way in Java to write in the middle of a file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best Way to Write Bytes in the Middle of a File in Java
I'm writing a program that modifies a PostScript file to add print properties, so I need to add lines in the middle of the file. These PostScript files are very large, and I want to know if the code I'm using is the most efficient. This code reads the source file and writes a temporary file adding a line where is needed.
Writer out = null;
Scanner scanner = null;
String newLine = System.getProperty("line.separator");
scanner = new Scanner(new FileInputStream(fileToRead));
out = new OutputStreamWriter(new FileOutputStream(fileToWrite));
String line;
while(scanner.hasNextLine()){
line = scanner.nextLine();
out.write(line);
out.write(newLine);
if(line.equals("%%BeginSetup")){
out.write("<< /Duplex true /Tumble true >> setpagedevice");
out.write(newLine);
}
}
scanner.close();
out.close();
Any help will be appreciated, thanks in advance.
Most of the old answers found on SO uses/links the old java.io.*
Oracle has nice examples how to do this using the "new" java 7 java.nio.* packages (usually with much better performance)
http://docs.oracle.com/javase/tutorial/essential/io/rafs.html
See RandomAccessFile and its example here: Fileseek - You can seek to a particular location in the file and write to it there.

Categories

Resources