Save content of File as String in Java? - java

I was working a little bit with config files and file reader classes in java.
I always read/wrote in the files with arrays because I was working with objects.
This looked a little bit like this:
public void loadUserData(ArrayList<User> arraylist) {
try {
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
for(String line : lines) {
String[] userParams = line.split(";");
String name = userParams[0];
String number= userParams[1];
String mail = userParams[2];
arraylist.add(new User(name, number, mail));
}
} catch (IOException e) {
e.printStackTrace();
}
}
This works fine, but how can I save the content of a file as only one single string?
When I read a file, the string I use should be the exact same as the content of the file (without the use of arrays or line splits).
how can I do that?
Edit:
I try to read a SQL-Statement out of a file to use it with JDBC later on. That's why I need the content of the File as a single String

This method will work
public static void readFromFile() throws Exception{
FileReader fIn = new FileReader("D:\\Test.txt");
BufferedReader br = new BufferedReader(fIn);
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
String text = sb.toString();
System.out.println(text);
}

I hope this is what you need:
public void loadUserData(ArrayList<User> arraylist) {
StringBuilder sb = new StringBuilder();
try {
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
for(String line : lines) {
// String[] userParams = line.split(";");
//String name = userParams[0];
//String number= userParams[1];
//String mail = userParams[2];
sb.append(line);
}
String jdbcString = sb.toString();
System.out.println("JDBC statements read from file: " + jdbcString );
} catch (IOException e) {
e.printStackTrace();
}
}
or maybe this:
String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);

Just do that:
final FileChannel fc;
final String theFullStuff;
try (
fc = FileChannel.open(path, StandardOpenOptions.READ);
) {
final ByteBuffer buf = ByteBuffer.allocate(fc.size());
fc.read(buf);
theFullStuff = new String(buf.array(), theCharset);
}
nio for the win! :p

You could always create a Buffered reader e.g.
File anInputFile = new File(/*input path*/);
FileReader aFileReader = new FileReader(anInputFile);
BufferedReader reader = new BufferedReader(aFileReader)
String yourSingleString = "";
String aLine = reader.readLine();
while(aLine != null)
{
singleString += aLine + " ";
aLine = reader.readLine();
}

Related

Multi word replacement within xml file using java

I have an xml-base .tbx file containing code like this:
<descripGrp>
<descrip type="subjectField">406001</descrip>
</descripGrp>
<langSet xml:lang="en">
<tig>
<term>competence of the Member States</term>
<termNote type="termType">fullForm</termNote>
<descrip type="reliabilityCode">3</descrip>
</tig>
</langSet>
<langSet xml:lang="pl">
<tig>
<term>kompetencje państw członkowskich</term>
<termNote type="termType">fullForm</termNote>
<descrip type="reliabilityCode">3</descrip>
</tig>
</langSet>
</termEntry>
<termEntry id="IATE-290">
<descripGrp>
<descrip type="subjectField">406001</descrip>
</descripGrp>
I want to search and replace within entire (almost 50 MiB) file for codes from the field "subjectField" and replace the with proper text, eg.
406001 is for Political ideology, 406002 for Political institution.
I have a table with codes and corresponding names:
406001 Political ideology
406002 Political institution
406003 Political philosophy
There's five hundred of such codes so doing it by hand would take like forever.
I'm not a programmer (I'm learnig) but I know a little java so I made some little app which, I supposed, would help me, however the result is discouraging (luckily I'm not discouraged :))
That's what I wrote, the result is that it works extremely slow, doesn't replace those codes at all. It processed 1/5 of the file in 15 minutes (!). Additionally there are no new line characters in the output file so the entire xml code is in one line.
Any tips on which way I should go?
File log= new File("D:\\IATE\\export_EN_PL_2017-03-07_All_Langs.tbx"); // TBX file to be processed
File newe = new File("D:\\IATE\\now.txt"); // output file
String search = "D:\\IATE\\org.txt"; // file containing codes "40600" etc
String replace = "D:\\IATE\\rplc.txt"; // file containing names
try {
FileReader fr = new FileReader(log);
String s;
String s1;
String s2;
String totalStr = "";
String tot1 = "";
String tot2 = "";
FileReader fr1 = new FileReader(search);
FileReader fr2 = new FileReader(replace);
try (BufferedReader br = new BufferedReader(fr)) {
try (BufferedReader br1 = new BufferedReader(fr1)) {
try (BufferedReader br2 = new BufferedReader(fr2)) {
while ((s = br.readLine()) != null) {
totalStr += s;
while((s1 = br1.readLine()) != null){
tot1 += s1;
while ((s2 = br2.readLine()) != null){
tot2 += s2;
}
}
totalStr = totalStr.replaceAll(tot1, tot2);
FileWriter fw = new FileWriter(newe);
fw.write(totalStr);
fw.write("\n");
fw.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Its going to take a lot of redundant work to traverse 2 files to get matching values. Before you replace values in the .tbx files you should set up a properties file to read from. Here's a function that would do that:
public static Properties getProps(String pathToNames, String pathToNumbers){
Properties prop = new Properties();
try{
File names = new File(pathToNames);
BufferedReader theNames = new BufferedReader( new InputStreamReader (new FileInputStream(names)));
File numbers = new File(pathToNumbers);
BufferedReader theNumbers = new BufferedReader( new InputStreamReader (new FileInputStream(numbers)));
String name;
String number;
while(((name = theNames.readLine())!= null)&&((number = theNumbers.readLine())!= null)){
prop.put(number, name);
}
theNames.close();
theNumbers.close();
}catch(Exception e){
e.printStackTrace();
}
return prop;
}
Assuming you are using Java 8, you can check that the function is working with this:
thePropertiesFile.forEach((Object key, Object value) ->{
System.out.println(key+ " " +value);
});
Now you can write a function that will convert properly. Use a PrintStream to achieve the output functionality you want.
static String workingDir = System.getProperty("user.dir");
public static void main(String[] args){
Properties p = getProps(workingDir+"path/to/names.txt",workingDir+"path/to/numbers.txt");
File output = new File(workingDir+"path/to/output.txt");
try {
PrintStream ps = new PrintStream(output);
BufferedReader tbx = new BufferedReader(new InputStreamReader (new FileInputStream(new File(workingDir+"path/to/the.tbx"))));
String currentLine;
String theNum;
String theName;
int c; //temp index
int start;
int end;
while((currentLine = tbx.readLine()) != null){
if(currentLine.contains("subjectField")){
c = currentLine.indexOf("subjectField");
start = currentLine.indexOf(">", c)+1;
end = currentLine.indexOf("<", c);
theNum = currentLine.substring(start, end);
theName = p.getProperty(theNum);
currentLine = currentLine.substring(0,start)+theName+currentLine.substring(end);
}
ps.println(currentLine);
}
ps.close();
tbx.close();
} catch (IOException e) {
e.printStackTrace();
}
}
For numbers that don't exist, this will replace them with a null string. You can update that for your specific use.
If theNum contains multiple values, split into an array:
theName = "";
if(theNum.contains(","){
int[] theNums = theNum.split(",");
for (int num : theNums) {
theName += p.getProperty(num);
theName += ",";
}
theName = theName.replaceAll(",$", ""); //get rid of trailing comma
}
else
theName = p.getProperty(theNum);

How to keep some Strings in a text file?

I have a text file which has a format like this:
ab
cd
ef
gh
ij
..
I want to erase Strings after "ef", I mean after running my program the text file structure be like this:
ab
cd
ef
I'm using netbeans IDE and using java codes. Could any one help?
It's my tried code but it just keeps Strings before "ef" in a String, but I have no idea how to do the else!
BufferedReader br = new BufferedReader(new FileReader("E:\\info.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (!(line.equals("ef"))) {
sb.append(line);
// sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
System.out.print(everything);
// System.out.print(sb);
} finally {
br.close();
}
Here is an example to correct your file
final String fileName = "E:\\info.txt";
String everything = "";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (!(line.equals("ef"))) {
sb.append(line).append("\n");
// sb.append(System.lineSeparator());
line = br.readLine();
}
sb.append(line);
everything = sb.toString();
System.out.print(everything);
}
final File file = new File(fileName);
file.delete();
try (FileWriter writer = new FileWriter(fileName)) {
writer.write(everything);
}
You could use Apache commons-io's FileUtils like in the following example:
private final String FILE_NAME = "E:\\info.txt";
public void test() throws IOException {
File file = new File(FILE_NAME);
List<String> strings = FileUtils.readLines(file);
int ef = strings.indexOf("ef");
List<String> stringBeforeEF = strings.subList(0, ef);
FileUtils.writeLines(file, stringBeforeEF);
}

How to create item objects from reading a text file?

I'm trying to read data from a text file and create Item Objects with it.
Item Objects have fields String title, String formatt, boolean onLoan, String loanedTo and String dateLoaned. In my save()method, I print every object to a text file in a new line and the fields are seperated by "$" (dollar sign). How can I read the text file line by line and create a new object from each line and add it to an array.
TextFile Example:
StarWars$DVD$false$null$null
Aliens$Bluray$true$John$Monday
public void save() {
String[] array2 = listForSave();
PrintWriter printer = null;
try {
printer = new PrintWriter(file);
for (String o : array2) {
printer.println(o);
}
printer.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
public void open(){
try{
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
}catch ( IOException e ) {
e.printStackTrace();
}
}
Thanks everyone. Here's my final code:
public void open(){
try{
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
String[] strings;
while ((line = bufferedReader.readLine()) != null) {
strings = line.split("\\$");
String title = strings[0];
String format = strings[1];
boolean onLoan = Boolean.parseBoolean(strings[2]);
String loanedTo = strings[3];
String dateLoaned = strings[4];
MediaItem superItem = new MediaItem(title,format, onLoan,loanedTo,dateLoaned);
items.add(superItem);
}
fileReader.close();
}catch ( IOException e ) {
e.printStackTrace();
}
}
String line = // input line e.g. "Aliens$Bluray$true$John$Monday"
String[] strings = line.split("\\$"); // use regex matching "$" to split
String title = strings[0];
String formatt = strings[1];
boolean onLoan = Boolean.parseBoolean(strings[2]);
String loanedTo = strings[3];
String dateLoaned = strings[4];
// TODO: create object from those values
Maybe you need to handle null differently (in case you want the String "null" to be converted to null); note that you can't distinguish if null or "null" was saved.
This function converts "null" to null and returns the same string otherwise:
String convert(String s) {
return s.equals("null") ? null : s;
}
Reading the objects to an array
Since you don't know the number of elements before reading all lines, you have to work around that:
Write the number of objects in the file as first line, which would allow you to create the array before reading the first object. (Use Integer.parseInt(String) to convert the first line to int):
public void save() {
String[] array2 = listForSave();
PrintWriter printer = null;
try {
printer = new PrintWriter(file);
printer.println(array2.length);
for (String o : array2) {
printer.println(o);
}
printer.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
public void open(){
try{
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
int arraySize = Integer.parseInt(stringBuffer.readLine());
Object[] array = new Object[arraySize];
int index = 0;
String line;
while ((line = bufferedReader.readLine()) != null) {
// split line and create Object (see above)
Object o = // ...
array[index++] = o;
}
//...
}catch ( IOException e ) {
e.printStackTrace();
}
//...
}
or
Use a Collection, e.g. ArrayList to store the objects and use List.toArray(T[]) to get an array.
quick and dirty solution might be...
public void open(){
try{
ArrayList<Item> list = new ArrayList<Item>(); //Array of your ItemObject
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
Item itm = new Item(); //New Item Object
String [] splitLine = line.split("\\$");
item.title = splitLine[0];
item.format = splitLine[1];
item.onLoan = Boolean.parseBoolean(splitLine[2]);
item.loanedTo = splitLine[3];
item.dateLoaned = splitLine[4];
list.add(itm);
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
}catch ( IOException e ) {
e.printStackTrace();
}
}
But this is won't scale if you need to re-arrange or add new fields.
You could try this to "parse" every line of your file
String[] result = "StarWars$DVD$false$null$null".split("\\$");
for (int i=0; i<result.length; i++) {
String field = result[i]
... put the strings in your object ...
}

How can i split a textfile and store 2 values in one line?

I have a text file -> 23/34 <- and I'm working on a Java program.
I want to store them out in String One = 23 and anotherString = 34 and put them together to one string to write them down in a text file, but it dosen't work. :( Everytime it makes a break. Maybe because the split method but I don't know how to separate them.
try {
BufferedReader in = new BufferedReader (new FileReader (textfile) );
try {
while( (textfile= in.readLine()) != null ) {
String[] parts = textfileString.split("/");
String one = parts[0];
}
}
}
When I print or store one + "/" + anotherString, it makes a line-break at one but I want it all in one line. :(
public static void main(String[] args) throws Exception {
File file = new File("output.txt");
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String string1 = line.split("/")[0];
String string2 = line.split("/")[1];
bw.write(string1 + string2 + "\n");
bw.flush();
}
br.close();
bw.close();
}
On file:
23/34
Resulted in output.txt containing:
2334
You need to read in each line, and split it on your designated character ("/"). Then assign string1 to the first split, and string2 to the second split. You can then do with the variables as you want. To output them to a file, you simply append them together with a + operator.
You have never shown us how you are writing the file, so we can't really help you with your code. This is a bit of a more modern approach, but I think it does what you want.
File infile = new File("input.txt");
File outfile = new File("output.txt");
try (BufferedReader reader = Files.newBufferedReader(infile.toPath());
BufferedWriter writer = Files.newBufferedWriter(outfile.toPath())) {
String line;
while ((line = reader.readLine()) != null) {
String parts[] = line.split("/");
String one = parts[0];
String two = parts[1];
writer.write(one + "/" + two);
}
} catch (IOException ex) {
System.err.println(ex.getLocalizedMessage());
}
InputStream stream = this.getClass().getResourceAsStream("./test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
String[] parts = currentLine.split("/");
System.out.println(parts[0] + "/" + parts[1]);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}

very long string as a response of web service

I am getting a really long string as the response of the web service I am collecting it in the using the StringBuilder but I am unable to obtain the full value I also used StringBuffer but had no success.
Here is the code I am using:
private static String read(InputStream in ) throws IOException {
//StringBuilder sb = new StringBuilder(1000);
StringBuffer sb = new StringBuffer();
String s = "";
BufferedReader r = new BufferedReader(new InputStreamReader( in ), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
s += line;
} in .close();
System.out.println("Response from Input Stream Reader >>>" + sb.toString());
System.out.println("Response from Input S >>>>>>>>>>>>" + s);
return sb.toString();
}
Any help is appreciated.
You can also split the string in array of strings in order to see all of them
String delimiter = "put a delimiter here e.g.: \n";
String[] datas=sb.toString().split(delimiter);
for(String string datas){
System.out.println("Response from Input S >>>>>>>>>>>>" + string);
}
The String may not print entirely to the console, but it is actually there. Save it to a file in order to see it.
I do not think that your input is too big for a String, but only not shown to the console because it doesn't accept too long lines. Anyways, here is the solution for a really huge input as characters:
private static String[] readHugeStream(InputStream in) throws IOException {
LinkedList<String> dataList = new LinkedList<>();
boolean finished = false;
//
BufferedReader r = new BufferedReader(new InputStreamReader(in), 0xFFFFFF);
String line = r.readLine();
while (!finished) {
int lengthRead = 0;
StringBuilder sb = new StringBuilder();
while (!finished) {
line = r.readLine();
if (line == null) {
finished = true;
} else {
lengthRead += line.length();
if (lengthRead == Integer.MAX_VALUE) {
break;
}
sb.append(line);
}
}
if (sb.length() != 0) {
dataList.add(sb.toString());
}
}
in.close();
String[] data = dataList.toArray(new String[]{});
///
return data;
}
public static void main(String[] args) {
try {
String[] data = readHugeStream(new FileInputStream("<big file>"));
} catch (IOException ex) {
Logger.getLogger(StackoverflowStringLong.class.getName()).log(Level.SEVERE, null, ex);
} catch (OutOfMemoryError ex) {
System.out.println("out of memory...");
}
}
System.out.println() does not print all the characters , it can display only limited number of characters in console. You can create a file in SD card and copy the string there as a text document to check your exact response.
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Responsefromserver");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, "response.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(totalResponse);
writer.flush();
writer.close();
}
catch(IOException e)
{
System.out.println("Error:::::::::::::"+e.getMessage());
throw e;
}

Categories