Solved

JAVA - Load string from file

Posted on 2009-07-12
8
2,804 Views
Last Modified: 2013-11-21
HI, im trying to load words (censor) from a file

this is how i currently load it:
 public String badWords[] = {"xxx", "xxx", "xxx"};
and i can add more by just going ,"newword" inside the {}

but now i have lots of words, i need to load it from a file "badwords.cfg"

can someone provide some really simple code, that i can use?

by the way, i would like not to have to put a number of the amot, so i  can just add another without compiling...

THANKS
0
Comment
Question by:gamerx93
8 Comments
 
LVL 23

Accepted Solution

by:
Ajay-Singh earned 43 total points
ID: 24833787
You can keep the words line-by-line and use BufferedReader
to read line. Example here
 
http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html
0
 

Author Comment

by:gamerx93
ID: 24833790
yes, but then how do i load them into an array?
0
 
LVL 8

Assisted Solution

by:ozlevanon
ozlevanon earned 41 total points
ID: 24833930
Here is a sample code. It reads lines from a file, and puts each line in a set which is then converted to an array.

BufferedReader br = new BufferedReader(new FileReader("badwords.cfg"));

			Set<String> words = new HashSet<String>();

			while (true)

			{

				String line = br.readLine();

				if (line == null)

				{

					break;

				}

				words.add(line.trim());

			}

			br.close();
 

			String []array = new String[words.size()];

			words.toArray(array);

			System.out.println("array = " + Arrays.toString(array));

Open in new window

0
Save on storage to protect fatherhood memories

You're the dad who has everything. This Father's Day, make sure your family memories are protected. My Passport Ultra has automatic backup and password protection to keep your cherished photos and videos safe. With up to 3TB, you have plenty of room to hold the adventures ahead.

 
LVL 2

Expert Comment

by:rnevet
ID: 24833990
If you don't need to edit the text file... the simplest way is using serialize.

http://www.java2s.com/Code/Java/Collections-Data-Structure/Serializingavector.htm
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 41 total points
ID: 24839460
The best way is just to treat the file as a List of String:

http://technojeeves.com/joomla/index.php/free/74-string-list
0
 
LVL 2

Expert Comment

by:guneshraj
ID: 24844245
     public static String getContents(File aFile) {
          StringBuffer contents = new StringBuffer();
          BufferedReader input = null;
          try {
                 InputStreamReader fr=new InputStreamReader(new FileInputStream(aFile),"UTF8");
                input = new BufferedReader( fr );
            String line = null; //not declared within while loop
            while (( line = input.readLine()) != null){
              contents.append(line);
              contents.append(System.getProperty("line.separator"));
            }
          }
          catch (FileNotFoundException ex) {
            //ex.printStackTrace();
          }
          catch (IOException ex){
            //ex.printStackTrace();
          }
          finally {
            try {
              if (input!= null) {
                input.close();
              }
            }
            catch (IOException ex) {
              //ex.printStackTrace();
            }
          }
          return contents.toString();
        }

--
//{"xxx", "xxx", "xxx"}; to String Array
String words = getContents(new File("badwords.cfg"));
// Now remove all the control chars
words = words.replaceAll("{", "");
words = words.replaceAll("};", "");
words = words.replaceAll("\"", "");
words = words.replaceAll("\n", "");
// All the chars that are not part of the plan

String badwords[] = words.split("[,]");

** There you go, Hope this example helps.

Gunesh





0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24844309
You don't need to read line by line actually

String[] badWords = fileToString("badwords.cfg").split("[\r\n]");

See

http://technojeeves.com/joomla/index.php/free/70-reading-a-file-into-a-string-in-java
0

Featured Post

Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Python Assistance 7 71
SUM 2 INTEGER ARRAYS INTO 1 10 92
Java Loop 6 48
Help with a redirect in web.config file 8 20
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

930 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now