I am currently reading in a file into java where the file contains list of ("char symbol" "tab" "6 comma seperated booleans" "new line")
I am reading it in fine and splitting it up ok - however i have a problem whereby the pound sign and speech marks are being read in as a black diamond with a question mark in it. This is screwing everything up as i need to be able to identify which codes go with which char symbol.
I am reading in using:
public void read()
{
int i = 0;
try{
// Open the file
InputStream is = am.open("combinations.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(is);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null && i < 53) {
String[] sep1 = strLine.split("\t");
String[] sep2 = sep1[1].split(",");
entries[i] = new Entry(sep1[0].charAt(0), new CellPattern(Boolean.valueOf(sep2[0]),
Boolean.valueOf(sep2[1]),Boolean.valueOf(sep2[2]),Boolean.valueOf(sep2[3]),
Boolean.valueOf(sep2[4]),Boolean.valueOf(sep2[5])));
i++;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
It is an encoding problem, try changing your BufferedReader line to:
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
I'm not sure which encoding you'll need, so you may want to try a few different ones.
Edit:
Try "ISO-8859-1"
Related
So if I have a txt file like this:
scissors 3
papers 5
staplers 2
How do I only read the integers with a bufferedreader and not using scan.
try {
BufferedReader reader = new BufferedReader(new FileReader("Supplies.txt"));
String line = "";
while((line=reader.readLine())!=null){
System.out.println(line);
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex);
}
How do I only read the integers with a bufferedreader and not using scan.
Assuming I understand your question, you could use your current code, and add a regular expression to remove everything that isn't a digit before parsing the int value. Like,
while ((line = reader.readLine()) != null) {
int i = Integer.parseInt(line.replaceAll("\\D+", ""));
System.out.println(i);
}
You should close() your reader when you finish with it, otherwise you leak a file handle. I believe the best solution is a try-with-resources. Like,
try (BufferedReader reader = new BufferedReader(new FileReader("Supplies.txt"))) {
// BufferedReader reader = new BufferedReader(new FileReader("Supplies.txt"));
I am trying to read lines of text from the console. The number of lines is not known in advance. The BufferedReader.readLine() method reads a line but after the last line it waits for input from the console. What should be done in order to avoid this?
Please see the code snippet below:
public static String[] getLinesFromConsole() {
String strLine = "";
try {
// Get the object of DataInputStream
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null)
strLine += line + "~"; //edited
isr.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return strLine.split("~");
}
The below code might fix, replace text exit with your requirement specific string
public static String[] getLinesFromConsole() {
String strLine = "";
try {
// Get the object of DataInputStream
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null && !line.equals("exit") )
strLine += br.readLine() + "~";
isr.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return strLine.split("~");
}
When reading from the console, you need to define a "terminating" input since the console (unlike a file) doesn't ever "end" (it continues to run even after your program terminates).
There are several solutions to your problem:
Put the input in a file and use IO redirection: java ... < input-file
The shell will hook up your process with the input file and you will get an EOF.
Type the EOF-character for your console. On Linux and Mac, it's Ctrl+D, on Windows, it's Ctrl+Z + Enter
Stop when you read an empty line. That way, the user can simply type Enter.
PS: there is a bug in your code. If you call readLine() twice, it will skip every second line.
I want to write a simple java program to read in a text file and then write out a new file whenever a blank line is detected. I have seen examples for reading in files but I don't know how to detect the blank line and output multiple text files.
fileIn.txt:
line1
line2
line3
fileOut1.txt:
line1
line2
fileOut2.txt:
line3
Just in case your file has special characters, maybe you should specify the encoding.
FileInputStream inputStream = new FileInputStream(new File("fileIn.txt"));
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(streamReader);
int n = 0;
PrintWriter out = new PrintWriter("fileOut" + ++n + ".txt", "UTF-8");
for (String line;(line = reader.readLine()) != null;) {
if (line.trim().isEmpty()) {
out.flush();
out.close();
out = new PrintWriter("file" + ++n + ".txt", "UTF-8");
} else {
out.println(line);
}
}
out.flush();
out.close();
reader.close();
streamReader.close();
inputStream.close();
I don't know how to detect the blank line..
if (line.trim().length==0) { // perform 'new File' behavior
.. and output multiple text files.
Do what is done for a single file, in a loop.
You can detect an empty string to find out if a line is blank or not. For example:
if(str!=null && str.trim().length()==0)
Or you can do (if using JDK 1.6 or later)
if(str!=null && str.isEmpty())
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
// Line is empty
}
}
The above code snippet can be used to detect if the line is empty and at that point you can create FileWriter to write to new file.
Something like this should do :
public static void main(String[] args) throws Exception {
writeToMultipleFiles("src/main/resources/fileIn.txt", "src/main/resources/fileOut.txt");
}
private static void writeToMultipleFiles(String fileIn, String fileOut) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileIn))));
String line;
int counter = 0;
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileOut))));
while((line=br.readLine())!=null){
if(line.trim().length()!=0){
wr.write(line);
wr.write("\n");
}else{
wr.close();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut + counter)));
wr.write(line);
wr.write("\n");
}
counter++;
}
wr.close();
}
I'm trying to read a simple text file that contains the following:
LOAD
Bill's Beans
1200
20
15
30
QUIT
I need to store and print the contents line by line. I am doing so using the following code:
String inputFile = "(file path here)";
try {
Scanner input = new Scanner(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String currentLine = "";
while (!currentLine.equals("QUIT}")){
currentLine = input.nextLine();
System.out.println(currentLine);
}
input.close();
However, the output is very "messy". I am trying to avoid storing all new line characters and anything else that doesn't appear in the text file. Output is:
{\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf540
{\fonttbl\f0\fmodern\fcharset0 Courier;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww9000\viewh8400\viewkind0
\deftab720
\pard\pardeftab720\ql\qnatural
\f0\fs26 \cf0 LOAD\
Bill's Beans\
1200\
20\
15\
30\
QUIT}
Any help would be greatly appreciated, thank you!
This looks like you're reading a RTF file, isn't that so, by any chance?
Otherwise, I found reading text files is most natural for me using this construct:
BufferedReader reader = new BufferedReader(
new FileReader(new File("yourfile.txt")
);
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
// do whatever with the text line
}
Because this is an RTF file, look into this for example: RTFEditorKit
If you insist on writing your own RTF reader, the correct approach would be for you to extend FilterInputStream and handle the RTF metadata in its implementation.
Just add following code into your class, then call it with path parameter. it returns all lines as List object
public List<String> readStudentsNoFromText(String path) throws IOException {
List<String> result = new ArrayList<String>();
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(new File(path));
// 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);
result.add(strLine.trim());
}
//Close the input stream
in.close();
return result;
}
so i'm trying to read from a file a number of lines, and after that put them in a String[]. but it doesn't seem to work. what have i done wrong?
String[] liniiFisier=new String[20];
int i=0;
try{
FileInputStream fstream = new FileInputStream("textfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
liniiFisier[i]=strLine;
i++;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
for(int j=0;j<i;j++)
System.out.println(liniiFisier[i]);
Change that last line to
System.out.println(liniiFisier[j]); // important: use j, not i
You should tell us what's happening and what problem occurred.
But I yet see some errors:
Imagine your file has more than 20 lines, so you'll try to access liniiFisier[20], but this field is not present! Results in ArrayIndexOutOfBounds
In your for loop you are iterating j but always using i...
Creating the BufferedReader can be done in less code:
FileReader fr = new FileReader ("textfile.txt");
BufferedReader br = new BufferedReader (fr);
Since I don't know about your particular problem this might not solve it, so please provide more information ;-)