I'm making a game in Java, but can't figure out how to get information from a text file so that I can load the game. I have the saved files set up so that on every line there is the name of a method in my Main program. What I need to do is to look in a certain line for text and execute the method that the text is referring to.
This should do it. Obviously you'll need to handle exceptions:
public class FileReaderTest
{
public static void main(String[] args) throws IOException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
final FileReaderTest object = new FileReaderTest();
final BufferedReader reader = new BufferedReader(new FileReader(new File("/path/to/file")));
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
object.getClass().getMethod(line).invoke(object);
}
}
}
Now, this is assuming that you are talking about a .txt file.
I/O is the basic Idea, If you master that, then you are set. I stands for input, and O, for Output.
Now, you need to make an variable equal to inputStream.readInt();
EDIT:
But for more help, you can also go with reading
Reading a text file in java
Hope this helps!
Related
Should I add a method and do not call throws in main?
Is that appropriate?
How do I write it? I do not know how to write.
private static String fileName = "C:\\fruit.csv";
public static void main(String[] args) throws
IOException{
BufferedReader br = new BufferedReader(new
FileReader(fileName));
TreeMap<String,Integer> tm = new
TreeMap<String,Integer>();
String line;
Logger logger = Logger.getLogger("Sample");
BasicConfigurator.configure();
logger.setLevel(Level.DEBUG);
try{
while((line = br.readLine()) != null){
String[] words = line.split("\\s");
for(String s : words){
if(!tm.containsKey(s)){
tm.put(s,1);
logger.debug(s+""+tm.get(s)+"N");}else{
tm.put(s,tm.get(s).intValue()+1);
logger.debug(s+""+tm.get(s)+"N");}}}
}catch(IOException e){
logger.debug("Error");
}finally{ br.close()}
Writer fw = new FileWriter("C:\\count.properties");
Properties p =new Properties();
for(String key : tm.keySet()){
p.setProperty(key,String.valueOf(tm.get(key)));
}p.store(fw,"fruit");}}}
Why is it inappropriate? Who says it is?
It entirely depends on the program, so broadly claiming that "it is inappropriate to throws at main" is wrong1.
What do you think should happen if an exception occurs? It is your decision to make, and the decision likely depends heavily on the purpose of the program.
It is an exception, so you likely want it printed, with a stacktrace so you can figure out where and why. Which is exactly what the java command does when main throws an exception, so why should you catch it, just to do the very same thing yourself?
Sure, if it is a command-line utility program, you'd likely want to catch the exception (including RuntimeException and Error), to print a one-line error message, without stacktrace, and then end the program with an exit code. But not all java programs are command-line utility programs.
1) Anyway, that is my opinion on the topic.
So I am using the following code to write to a file in Java, the text prints fine, but it has strange characters between the letters.
public static void foo() throws IOException{
static RandomAccessFile configFile;
configFile.writeChars("#Minecraft server properties");
configFile.close();
}
I was searching for answer and everything pointed to incorrect usage of writeUTF() so I decided to try that instead which semi-fixed the issue, but I still have that character at the beginning of the line.
public static void foo() throws IOException{
static RandomAccessFile configFile;
configFile.writeUTF("#Minecraft server properties");
configFile.close();
}
My questions are: what is that char? Vim shows it as an # and what can I do to remove it?
That char is related with the encoding of the file you are creating.
Try using the following code instead:
public static void createConfigFile() throws IOException {
FileWriter writer = new FileWriter("PATH_TO_YOUR_CONFIG_FILE", false);
writer.append("#Minecraft server properties");
// Append any other content you need here.
writer.flush();
writer.close();
}
Hope that helps!
Below is my code that reads in a file, and then writes its contents to a new file. What I need to do is add in text between each line of text from the old file and put that in the new file. In this code, the file is read as a whole, so how do I change it to go through line by line and add text between each?
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class Webpage {
public static String readTextFile(String fileName) throws IOException {
String content = new String(Files.readAllBytes(Paths.get(fileName)));
return content;
}
public static List<String> readTextFileByLines(String fileName)throws IOException {
List<String> lines = Files.readAllLines(Paths.get(fileName));
return lines;
}
public static void writeToTextFile(String fileName, String content)throws IOException {
Files.write(Paths.get(fileName), content.getBytes(), StandardOpenOption.CREATE);
}
}
I think your readTextFileByLines will do what you want. You can iterate through the List and write out whatever you want before and after each line.
If you must use the readTextFile method, you could use split("\n") to turn the single big String (the whole file) into an array of Strings, one per line.
Hmm... the doc for Split (one argument) says that trailing empty strings won't be included in the result. So if your input file might contain empty lines at the end, you should use the two argument split with a very large second argument: split("\n", Long.MAX_VALUE);
Read the text file line by line and add new lines where you wish.
Put the read values with new lines in a string per line separated by \n.
Write in new text file.
If what you are trying to do is re-write each line with the same string before and after each time than you can use this code:
public static void main(String[] args) throws IOException {
addLines("/Users/Hamish/Desktop/file1.txt", "/Users/Hamish/Desktop/file2.txt");
}
public static void addLines(String fileName, String secondFile) throws IOException {
File file = new File(fileName);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
PrintWriter writer = new PrintWriter(secondFile, "UTF-8");
while ((line = br.readLine()) != null) {
writer.println("Random line before");
writer.println(line);
writer.println("Random line after");
}
br.close();
writer.close();
}
Effectively it reads the txt file line by line and before and after each line it will print something you specify.
If you want at the end you can also write:
file.delete();
to remove the first file.
If what you want to write before and after each line is specific than unfortunately I can't help you.
I have file where every line represents vertice. (format for example- 1.0 0.0 vertice A)
My task is to create method
public void read(InputStream is) throws IOException
Which would save X and Y values of vertices and then label of it "vertice A". I have no idea how to parse it properly:
public void read(InputStream is) throws IOException {
try {
Reader r = new InputStreamReader(is);
BufferedReader br = new BufferedReader(r);
while(br.readLine()!=null){
//something
}
} catch(IOException ex){
ex.printStackTrace();
}
}
also I need to create method
public void read(File file) throws IOException
which makes exactly the same but with file instead of stream. Can you tell me difference between these two methods?
A File represents a node on the filesystem, a stream is a representation of a sequence of data with a read head. Opening a file for reading results in an input stream. System.In is an example of an input stream for which you did not provide a file, it is the stream for stdin.
public void read(File file) throws IOException
{
//using your input stream method, read the passed file
//Create an input stream from the given file, and then call what you've already implemented.
read(new FileInputStream(file));
//I assume your read function closes the stream when it's done
}
I'd do the following and explain it through the code :)
public void read(InputStream is) throws IOException {
//You create a reader hold the input stream (sequence of data)
//You create a BufferedReader which will wrap the input stream and give you methods to read your information
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
handleVerticeValues(reader);
reader.close();
}
public void read(File file) throws IOException {
//You create a buffered reader to manipulate the data obtained from the file representation
BufferedReader reader = new BufferedReader(new FileReader(file));
handleVerticeValues(reader);
reader.close();
}
private void handleVerticeValues(BufferedReader reader) throws IOException {
//Then you can read your file like this:
String lineCursor = null;//Will hold the value of the line being read
//Assuming your line has this format: 1.0 0.0 verticeA
//Your separator between values is a whitespace character
while ((lineCursor = reader.readLine()) != null) {
String[] lineElements = lineCursor.split(" ");//I use split and indicates that we will separate each element of your line based on a whitespace
double valX = Double.parseDouble(lineElements[0]);//You get the first element before an whitespace: 1.0
double valY = Double.parseDouble(lineElements[1]);//You get the second element before and after an whitespace: 0.0
String label = lineElements[2];//You get the third element after the last whitespace
//You do something with your data
}
}
You can avoid using split by using StringTokenizer as well, that is another approach :).
As mentioned in the other answer, a file is only a representation of a node in your file system, it just point to an element existing in your file system but it not hold any data or information at this point of your internal file, I mean, just information as a file (if is a file, directory or something like that) (if it does not exist, you receive a FileNotFoundException).
The InputStream is a sequence of data, at this point, you should have information here which needs to be handled or read by a BufferedReader, ObjectInputStream or another component, depending on what you need to do.
For more info, you can also ask to your friendly API docs:
https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html
https://docs.oracle.com/javase/7/docs/api/java/io/File.html
Regards and... happy coding :)
import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
Above is the code I'm currently attempting to use, it compiles fine, then I get a runtime error of:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
I've googled the error and not had anything that helped (I only googled the first 3 lines of the error)
Basically, the program I'm writing is part of a bigger program. This part is to get information from a text file which is written like this:
Film one / 1.5
Film two / 1.3
Film Three / 2.1
Film Four / 4.0
with the text being the film title, and the float being the duration of the film (which will have 20 minutes added to it (For adverts) and then will be rounded up to the nearest int)
Moving on, the program is then to put the information in an array so it can be accessed & modified easily from the program, and then written back to the file.
My issues are:
I get a run time error currently, not a clue how to fix? (at the moment I'm just trying to read each line, and store it in an array, as a base to the rest of the program) Can anyone point me in the right direction?
I have no idea how to have a split at "/" I think it's something like .split("/")?
Any help would be greatly appreciated!
Zack.
Your code is working but it reads just one line .You can use bufferedReader here is an example import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And here is an split example class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
I wouldn't use a Scanner, that's for tokenizing (you get one word or symbol at a time). You probably just want to use a BufferedReader which has a readLine method, then use line.split("/") as you suggest to split it into two parts.
Lazy solution :
Scanner scan = ..;
scan.nextLine();