Solved

JAVA - Load string from file

Posted on 2009-07-12
8
2,814 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
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

Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

Question has a verified solution.

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

A short article about a problem I had getting the GPS LocationListener working.
This is an explanation of a simple data model to help parse a JSON feed
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

809 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