Store text in java

Java: Store text file content line by line into an array

Write a Java program to store text file content line by line in an array.

Sample Solution:

import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Arrays; public class Exercise14 < public static void main(String a[])< StringBuilder sb = new StringBuilder(); String strLine = ""; Listlist = new ArrayList(); try < BufferedReader br = new BufferedReader(new FileReader("/home/students/test.txt")); while (strLine != null) < strLine = br.readLine(); sb.append(strLine); sb.append(System.lineSeparator()); strLine = br.readLine(); if (strLine==null) break; list.add(strLine); >System.out.println(Arrays.toString(list.toArray())); br.close(); > catch (FileNotFoundException e) < System.err.println("File not found"); >catch (IOException e) < System.err.println("Unable to read the file."); >> > 
[Append this text.Append this text.Append this text., Append this text., Append this text.]

Flowchart: Store text file content line by line into an array

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

Best way to create enum of strings?

package test; /** * @author The Elite Gentleman * */ public enum Strings < STRING_ONE("ONE"), STRING_TWO("TWO") ; private final String text; /** * @param text */ Strings(final String text) < this.text = text; >/* (non-Javadoc) * @see java.lang.Enum#toString() */ @Override public String toString() < return text; >>

Alternatively, you can create a getter method for text.

You can now do Strings.STRING_ONE.toString();

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

How to store data in text file in java

Java Input-Output: Exercise-14 with Solution Write a java program to store text file content line by line into an array. But, i don’t know how to fetch the DTS status from code (which line should i execute?) and save it in text file.

How to store data in text file in java

How to store data in text file in java that has various attributes like name, author etc that will be inputted by the user on CLI. any Idea?

It sounds like the Java class that will suit you best is a FileWriter. However, if you are writing a file with Key=Value lines, then the Properties class might end up being the better choice.

«[S]tore data in text file» sounds like you want a readable format. You can use comma-separated value (CSV) files.

You can write your own CSV serializer (search on SO for «how to write csv java») or use a solution like the Java CSV library.

Use DataOutputStream and DataInputStream. Using this class make it easier to read integer, float, double data and others without needing to interpret if the read data should be an integer or a float data.

DataOutputStream dos = new DataOutputStream(fos);

 // // Below we write some data to the cities.dat. // DataOutputStream class have various method that allow // us to write primitive type data and string. There are // method called writeInt(), writeFloat(), writeUTF(), // etc. // dos.writeInt(cityIdA); dos.writeUTF(cityNameA); dos.writeInt(cityPopulationA); dos.writeFloat(cityTempA); dos.writeInt(cityIdB); dos.writeUTF(cityNameB); dos.writeInt(cityPopulationB); dos.writeFloat(cityTempB); dos.flush(); dos.close(); 

Java — Where and how to store text files for, I have an app that accesses words from a csv text files. Since they usually do not change I have them placed inside a .jar file and read them using .getResourceAsStream call. I really like this approach since I do not have to place a bunch of files onto a user’s computer — I just have one .jar file.. The problem is …

Storing data in text file

Below are my code for the checkDTS function. I have to store the status of the DTS in the separated text file in 10 minutes interval.

private boolean DTS_firstTime = true; private int num_of_DTS_tries = 0; private long interval_DTS = 5 * 60 * 1000; public void checkDTS() < // log.info("===Check DTS==="); if((System.currentTimeMillis() - remoteLane.getLastDTSReceived() >interval_DTS))< if(num_of_DTS_tries >= 5)< //if (ipc_reachable) < if (getStates().getLNK().isStatus()) < if (getStates().getDTS().isStatus() || DTS_firstTime) < log.info(getRemoteLane().getName() + ">>DTS Service Failed."); DTS_firstTime = false; getStates().getDTS().setStatus(false); getRemoteLane().setDTSMode(""); dataSyncStopPlayback = false; doDataSyncAlert(); doDataSyncDisplay(); > > remoteLane.setLastDTSReceived(System.currentTimeMillis()); num_of_DTS_tries = 0; > else < sendDTSCommand(Status.ISDTSUP, ""); >num_of_DTS_tries++; > else < // log.debug("DTS Mode: " +getRemoteLane().getDTSMode()); if (getRemoteLane().getDTSMode().equalsIgnoreCase(Status.OK))< //if (ipc_reachable) < if (getStates().getLNK().isStatus()) < // if (!getStates().getDTS().isStatus()) < // clrDataSyncDisplay(); // >getStates().getDTS().setStatus(true); dataSyncStopPlayback = true; dataSyncAlert = false; if (!alert && !discrepancyalert && !exitWarningAlert) < getLane().setRoadBackground(getLane().stateColor); >//clrDataSyncDisplay(); > > else if (getRemoteLane().getDTSMode().equalsIgnoreCase(Status.NG))< //if (ipc_reachable) < if (getStates().getLNK().isStatus()) < if (getStates().getDTS().isStatus() || DTS_firstTime) < log.info(getRemoteLane().getName() + ">>DTS Service Failed.."); DTS_firstTime = false; getStates().getDTS().setStatus(false); dataSyncStopPlayback = false; doDataSyncAlert(); doDataSyncDisplay(); try < PrintStream myconsole = new PrintStream (new File ("E://TMC//250216.y.txt")); System.setOut(myconsole); myconsole.print(); >catch (FileNotFoundException fx) < System.out.println(fx); >> > > // getStates().getDTS().setStatus(true); num_of_DTS_tries = 0; > this.repaint(); > 

I try to put this segment of code for the storing DTS status into the file.But then, I don’t know which line should i put in myconsole.print() since I am not that familiar with this code.

try < PrintStream myconsole = new PrintStream(new File("E://TMC//250216.y.txt")); System.setOut(myconsole); myconsole.print(); >catch (FileNotFoundException fx)

The existing example only show on how to create new file and store in it. But mine, i know how to create file. But, i don’t know how to fetch the DTS status from code (which line should i execute?) and save it in text file.

You may want to read the answer on creating and Writing to a File in Java.

// One creates the PrintWriter to print to a place. PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8"); // Then one prints each line. If you have an array of lines, you can print by iterating through that array. writer.println("The first line"); writer.println("The second line"); // Remember to close the writer. Though, if you use `try-with-resources`, that is no longer a problem. writer.close(); 

If you know what information you have and what format you want it saved into, simply write it out to disc. Your code in the try loop is unrevealing about what kind of information you want to write, so I can’t say more than this.

File io — How do I reference a resource in Java?, 2 Answers. Use ClassLoader.getResourceAsStream or Class.getResourceAsStream. The main difference between the two is that the ClassLoader version always uses an «absolute» path (within the jar file or whatever) whereas the Class version is relative to the class itself, unless you prefix the path …

Issues using getResource() with txt file (Java)

I have a setup in which I make use of a txt file (both reading and writing to it) in my program. At present I have it setup such that I use the local filepath on my machine, however I need to package it up into an executable JAR. To do this I’ve tried switching the filepath string over to the following:

String filepath = MyClass.class.getResource("/resources/textfile.txt"); 

However, when I run this I get a bunch of errors. After googling the method I found the similar method getResourceAsStream which I have also tried. This seems to return an InputStream object, however I need the filepath as a string ideally. Is this possible? If not what are my options?

Additional Info:

Here are the error messages I receive when trying to read & write to the txt file:

java.io.FileNotFoundException:/Users/Fred/Documents/Eclipse%20Projects/RandomProject/bin/resources/textfile.txt (No such file or directory) 

Well the code you’ve given won’t compile, because Class.getResource returns a URL , not a String . You can’t treat the resource as «just another file» — because it’s not.

You should basically change whatever needs to read the file to accept an InputStream instead of a filename, and then pass in the result of calling getResourceAsStream() .

The method returns URL, not String. It’s signature is public URL getResource(String name)

String filepath = MyClass.class.getResource("/resources/textfile.txt").getPath(); 

I have a setup in which I make use of a txt file (both reading and writing to it) in my program.

For read only, the resource can be in a Jar on the application class-path. It is very rare (in production) for resources on the application class-path to be writable. This text file will most probably need to be put in a reproducible path (e.g. a sub-directory of user.home — where the sub-dir is based on the package name) and used as a File from that path.

Or to put that a different way. I think you are pursuing the wrong path, to achieve the goal.

If you expect to directly write to a text file inside a JAR, my friend then you are wrong all the way! Please post some more code for us to understand what is it exactly you want to achieve and how you think it could be done.

Reading data from .txt file in java, 3 Answers. Sorted by: 5. Check out Properties. The Properties.load () method has the ability to load a «key=value» formatted file into a map of keys -> values. You can then access the data like theProperties.getProperty («path»). Note that you will have to trim leading/trailing double quotes off of the values if the file …

Java Exercises: Store text file content line by line into an array

Java Input-Output: Exercise-14 with Solution

Write a java program to store text file content line by line into an array.

Sample Solution :

import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Arrays;public class Exercise14 < public static void main(String a[])< StringBuilder sb = new StringBuilder(); String strLine = ""; Listlist = new ArrayList(); try < BufferedReader br = new BufferedReader(new FileReader("/home/students/test.txt")); while (strLine != null) < strLine = br.readLine(); sb.append(strLine); sb.append(System.lineSeparator()); strLine = br.readLine(); if (strLine==null) break; list.add(strLine); >System.out.println(Arrays.toString(list.toArray())); br.close(); > catch (FileNotFoundException e) < System.err.println("File not found"); >catch (IOException e) < System.err.println("Unable to read the file."); >> > 
[Append this text.Append this text.Append this text., Append this text., Append this text.]

Flowchart: Store text file content line by line into an array

Java Code Editor:

Previous: Write a Java program to read a file line by line and store it into a variable.
Next: Write a Java program to write and read a plain text file.

Printwriter — How to create a .txt file within the java, Furthermore, if you want to create a file in a relative path (say in a folder for example) you can do something like this: File folder = new File(«folderName»); folder.mkdir(); // create a folder in your current work space File file = new File(folder, «fileName.txt»); // put the file inside the folder …

Источник

Читайте также:  Rest post service java
Оцените статью