I'm coding in Java and I want to split my string. I want to split it at.
/* sort */
Yes I plan to split a .java file that I have read as a string so I need it to include "/* sort */". I'm creating a code that sorts Arrays that are predefined in java class file.
Exactly that and do another split at
}
and then I wanted help how to go about splitting up the array since I'll be left with
an example would be this
final static String[] ANIMALS = new String[] /* sort */ { "eland", "antelope", "hippopotamus"};
My goal would be to sort that Array inside a .java file and replace it. This is my current code
private void editFile() throws IOException {
//Loads the whole Text or java file into a String
try (BufferedReader br = new BufferedReader(new FileReader(fileChoice()))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
}
arrayCutOff = everything.split("////* sort *////");
for(int i = 0; i < arrayCutOff.length; i++){
System.out.println(arrayCutOff[i]);
}
}
This basically reads the whole .txt or .java file completely with the exact same formatting into one string. I planned to split it at /* sort */ and sort the array inside but I realized if I did that I probably can't replace it.
Considered your're using java 8 you might go this direction:
private void editFile() throws IOException {
List<String> lines = Files.readAllLines(Paths.get(fileChoice()));
String content = lines.stream().collect(Collectors.joining(System.lineSeparator()));
Stream.of(content.split(Pattern.quote("/* sort */"))).forEach(System.out::println);
}
However, the trick you're asking for is Pattern.quote, which dates back Java 5. It'll qoute a literal so it can be used as a literal in regExs and is a bit more convenient (and reliable I think) than wrestling around with backslashes...
Related
I have a text file in which I want to read in, remove all non-alphabetic characters and white space including the empty lines. Then convert the text to lowercase. This is what I have so far in terms of the code:
public static String replace(String file ){
String plaintext = "";
try{
Scanner input = new Scanner(new File(file));
while(input.hasNext()){
//text = text + input.nextLine();
plaintext = input.nextLine();
plaintext = plaintext.replaceAll("[^a-zA-Z]", "");
plaintext = plaintext.toLowerCase();
System.out.println(plaintext);
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("File not found. ");
}
return "";
}//end of replace method
The only problem I'm facing is that I am not sure how to removed the black lines of spaces in between each paragraph of the text file. My output shows like this:
csthesciencethatdealswiththetheoryandmethodsofprocessinginformationindigitalcomputersthedesignofcomputerhardwareandsoftwareandthe
applicationsofcomputers
itthedevelopmentimplementationandmaintenanceof
computerhardwareandsoftwaresystemstoorganizeandcommunicateinformation
electronicallyabbreviationit
computersaremanmadetoolsthataidusinsolvingotherproblemsabiologististryingtofigureouthowlifeworksphysicistsandchemistsaretryingtofigureouthowitemsreactinouruniversemathematiciansaretryingtofigureoutrulesformanmadesystems
anyresearchproblemthatmayimproveacomputerscapabilityofhelpingsolveaproblemoranyresearchproblemthatshedslightaboutanewwaytodosomethingwithacomputerispartofcs
mostexcitingresearchmedicalapplicationsexpertsystemsfordiagnosis
The code below should work; please note that it makes use of the JSR 203 API as far as file handling is concerned (since Java 7; in store for 10+ years for you to use) and of Java 8 for streams and their associated methods. Also note that it won't work with code points outside the BMP:
public static String trimFile(final String file)
throws IOException
{
final StringBuilder sb = new StringBuilder();
final Path path = Paths.get(file);
try (
final Reader r = Files.newBufferedReader(path);
) {
int c;
while ((c = r.read()) != -1)
if (Character.isLetter(c))
sb.appendCodePoint(c);
}
return sb.toString();
}
A little explanation here:
we don't need anything else than a Reader given the requirements; and even though Files.newBufferedReader() returns a BufferedReader, we don't care about reading line by line, therefore we downgrade it to a Reader, and we trust the JRE implementation to do its thing;
the read() method of a Reader returns an int... This is fine given the requirements (ie, we should not expect code points outside the BMP);
the Character.isLetter() implementation used is the one that takes an int as an argument, well, so what: as stated in the previous point, we don't expect code points outside the BMP, in which case this method behaves the same way as its counterpart expecting a char, so no harm done;
we do, however, have to use the appendCodePoint of StringBuilder; this class' .append method taking an int as an argument will append the string representation of the integer as an argument, but this is not what we want.
I have a file that looks like this:
Dwarf remains:0
Toolkit:1
Cannonball:2
Nulodion's notes:3
Ammo mould:4
Instruction manual:5
Cannon base:6
Cannon base noted:7
Cannon stand:8
Cannon stand noted:9
Cannon barrels:10
...
What is the easiest way to open this file, search for name and return the value of the field? I cannot use any external libraries.
What i have tried/is this ok?
public String item(String name) throws IOException{
String line;
FileReader in = new FileReader("C:/test.txt");
BufferedReader br = new BufferedReader(in);
while ((line = br.readLine()) != null) {
if(line.contains(name)){
String[] parts = line.split(":");
return parts[1];
}
}
return null;
}
As a followup to your code - it compiles and works ok. Be aware though, that / is not the correct path separator on Windows (\ is). You could've created the correct path using, for example: Paths.get("C:", "test.txt").toString(). Correct separator is defined as well in File.separator.
The task can be easily achieved using basic Java capabilities. Firstly, you need to open the the file and read its lines. It can be easily achieved with Files.lines (Path.get ("path/to/file")). Secondly, you need to iterate through all the lines returned by those instructions. If you do not know stream API, you can change value returned from Files.lines (...) from Stream to an array using String[] lines = Files.lines(Paths.get("path/to/file")).toArray(a -> new String[a]);. Now lines variable has all the lines from the input file.
You have to then split each line into two parts (String.split) and see whether first part equals (String.equals) what you're looking for. Then simply return the second one.
I'm trying to read a data file and save the different variables into an array list.
The format of the data file looks a little like this like this
5003639MATH131410591
5003639CHEM434111644
5003639PSYC230110701
Working around the bad formatting of the data file, I added commas to the different sections to make a split work. The new text file created looks something like this
5,003639,MATH,1314,10591
5,003639,CHEM,4341,11644
5,003639,PSYC,2301,10701
After creating said file, I tried to save the information into an array list.
The following is the snippet of trying to do this.
FileReader reader3 = new FileReader("example.txt");
BufferedReader br3 = new BufferedReader(reader3);
while ((strLine = br3.readLine())!=null){
String[] splitOut = strLine.split(", ");
if (splitOut.length == 5)
list.add(new Class(splitOut[0], splitOut[1], splitOut[2], splitOut[3], splitOut[4]));
}
br3.close();
System.out.println(list.get(0));
The following is the structure it is trying to save into
public static class Class{
public final String recordCode;
public final String institutionCode;
public final String subject;
public final String courseNum;
public final String sectionNum;
public Class(String rc, String ic, String sub, String cn, String sn){
recordCode = rc;
institutionCode = ic;
subject = sub;
courseNum = cn;
sectionNum = sn;
}
}
At the end I wanted to print out one of the variables to see that it's working but it gives me an IndexOutOfBoundsException. I wanted to know if I'm maybe saving the info incorrectly, or am I perhaps trying to get it to print out incorrectly?
You have a space in your split delimiter specification, but no spaces in your data.
String[] splitOut = strLine.split(", "); // <-- notice the space?
This will result in a splitOut array of only length 1, not 5 like you expect.
Since you only add to the list when you see a length of 5, checking the list for the 0th element at the end will result in checking for the first element of an empty list, hence your exception.
If you expect your data to have a comma or a space separating the characters then you would alter the split line to be:
String[] splitOut = strLine.split("[, ]");
The split takes a regular expression as an argument.
Rather than artificially adding commas I would look at String.substring in order to cut the line you have read into pieces. For example:
while ((strLine = br3.readLine())!=null) {
if (strLine.length() != 20)
throw new BadLineException("line length is not valid");
list.add(new Class(strLine.substring(0,1), strLine.substring(1,7), strLine.substring(7,11), strLine.substring(11,15), strLine.substring(15,19)));
}
[ Untested: my numbers might be out because I a bit knacked, but you get the idea ]
Below is how i count the number of lines in a text file. Just wondering is there any other methods of doing this?
while(inputFile.hasNext()) {
a++;
inputFile.nextLine();
}
inputFile.close();
I'm trying to input data into an array, i don't want to read the text file twice.
any help/suggestions is appreciated.
thanks
If you are using java 7 or higher version you can directly read all the lines to a List using readAllLines method. That would be easy
readAllLines
List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
Then the size of the list will return you number of lines in the file
int noOfLines = lines.size();
If you are using Java 8 you can use streams :
long count = Files.lines(Paths.get(filename)).count();
This will have good performances and is really expressive.
The downside (compared to Thusitha Thilina Dayaratn answer) is that you only have the line count.
If you also want to have the lines in a List, you can do (still using Java 8 streams) :
// First, read the lines
List<String> lines = Files.lines(Paths.get(filename)).collect(Collectors.toList());
// Then get the line count
long count = lines.size();
If you just want to add the data to an array, then I append the new values to an array. If the amount of data you are reading isn't large and you don't need to do it often that should be fine. I use something like this, as given in this answer: Reading a plain text file in Java
BufferedReader fileReader = new BufferedReader(new FileReader("path/to/file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
If you are reading in numbers, the strings can be converted to numbers, say for integers intValue = Integer.parseInt(text)
I do not have enough reputation to comment but #superbob answer is almost perfect, indeed you must ensure to pass Charset.defaultCharset() as 2nd parameter like :
Files.lines(file.toPath(), Charset.defaultCharset()).count()
That's because Files.lines used UTF-8 by default and then using as it is on non default UTF-8 system can produce java.nio.charset.MalformedInputException.
It's fixed! Thanks to Edgar Boda.
I created a class that should read a text file and put that into an array:
private static String[] parts;
public static void Start() throws IOException{
InputStream instream = new FileInputStream("Storyline.txt");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
int numberOfLines=0, numberOfActions;
String line = null, input="";
while((line=buffreader.readLine())!=null){
line=buffreader.readLine();
input+=line;
}
parts=input.split(";");
}
But, when I try and output the array, it only contains one string. The last from the file, that I put in.
Here's the file I read from:
0;0;
Hello!;
Welcome!To this.;
56;56;
So;
I think it's something in the loop; but trying to put parts[number] in there doesn't work... Any suggestions?
You want to read the whole file into an String first maybe:
String line = null;
String input = "";
while((line=buffreader.readLine())!=null){
input += line;
}
parts = input.split(";");
You are overwriting the string array parts in every iteration of your while loop, so that's why it only contains the last line.
To store the entire file contents, with fields split, you'll need a 2-dimensional array, not a 1-dimensional array. Assuming there are 5 lines in the file:
private static String[][] parts = new String[5][];
Then assign each split array to an element of parts each loop:
parts[i++]=line.split(";"); // Assuming you define "i" for the line number
Also, split by default discards trailing empty tokens. To retain them, use the two-arg overload of split that takes a limit parameter. Pass a negative number to retain all tokens.
parts[i++] = line.split(";", -1);
It will only contain the last line; you are reassigning parts every time:
parts = line.split(";");
This trashes the previous reference and reassigns a reference to a new array to it. A better way might be to use a StringBuilder and append the lines and then split later:
StringBuilder stringBuilder = new StringBuilder();
while((line=buffreader.readLine())!=null){
stringBuilder.append(line);
}
parts = stringBuilder.toString().split(";");
This way you will get everything you want in one array. If you want to split everything such that you have one array per line, you will need parts to be a two-dimensional array. But the drawback is that you will need to know how many lines will be there in the file. Instead, you can use List<String[]> to keep track of your arrays:
List<String[]> lineParts = new ArrayList<String[]>();
while((line=buffreader.readLine())!=null){
lineParts.add(line.split(";"));
}