Solved

JAVA - Load string from file

Posted on 2009-07-12
8
2,803 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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
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

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Join & Write a Comment

Suggested Solutions

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

760 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

20 Experts available now in Live!

Get 1:1 Help Now