JSF - Read a text file and diplay lines of text data on the web page
Hello,
For one of my projects, I need to display lines of text data on the web page using Java Server Faces Technology. The raw data could be from simple text files or sockets or anything. (Getting the data is not my issue but displaying is). Could anybody send answers with sample code. In servlet, one could do this by -
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
PrintWriter out = response.getWriter();
out.println("<html>");
out.println(DATA);
out.println(DATA);
out.println("</html>");
I am looking for similar solution.
Thanks in advance
DK
Thanks mjolinor. Works great!
Two questions.
1. Could you plz suggest how this could be modified so this code would read the file in or accept it from the pipeline instead of wrapping the (@' around the data?
2. Could you plz briefly describe some of the details of the code so I can further research and understand.
Thanks for your help.
Thanks for your help! SdeDot
1. It already reads in the file. The (@' .. '@) bits are just there to create a file using your test data to demonstrate that it works.
2. Not user what kind of "details" you want. There really isn't much there, and get-help on the cmdlets used should provide information on what's going on with them in that script.
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "
Similar Messages
-
Hello,
I have a text file and each line contains random text followed by an IP address as follows.
some text....172.30.25.30
some text.....172.30.85.10
some text..172.30.25.35
some text.......172.30.85.11
some text....172.30.15.1
some text...172.30.15.2
some text.......172.10.1.1
some text...172.20.4.2
some text..172.10.1.2
some text.....172.20.5.1
I'd like to create an output file which has only one entry for each unique entry in the file where either the first 2 or 3 octets are unique as follows:
Output File
172.30.25
172.30.85
172.30.15
172.10.1
172.20
Any suggestions are appreciated!
Thanks for your help! SdeDotThanks mjolinor. Works great!
Two questions.
1. Could you plz suggest how this could be modified so this code would read the file in or accept it from the pipeline instead of wrapping the (@' around the data?
2. Could you plz briefly describe some of the details of the code so I can further research and understand.
Thanks for your help.
Thanks for your help! SdeDot
1. It already reads in the file. The (@' .. '@) bits are just there to create a file using your test data to demonstrate that it works.
2. Not user what kind of "details" you want. There really isn't much there, and get-help on the cmdlets used should provide information on what's going on with them in that script.
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " " -
Reading text file and output (to stdout) a list of the unique words in the
Hi,
I have a main method as
main.java
package se.tmp;
public class Main
public static void main( String[] args )
WordAnalyzer.parse( args[0] );
and text file as
words.txt
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the requirement is like
I need create this WordAnalyzer class, implement the parse method, and then commit the file. This method takes a single parameter, the filename of the file to parse. The method should read this file and output (to stdout) a list of the unique words in the file along with the number of times each appears in the file.
Can anyone please help me on this?
Thanks.Where are you having problems?
-
Read bytes in file and print in clear text
Hi
I'm using hsql and use cached tables. This results in all data beeing stored in a binary file (Some of the data is stored in plain text though, but encrypted). The binary data starts and ends with ' (singlequote), the format is hexadecimal. How can I read this file and present all data in plain text, there is no need to decrypt the encrypted strings though.
Example of how the data is stored in the file:
W@ ` � M 43.6 Torticollis (nacksp��rr) h � X M 50 !Disksjukdom med halsryggssm��rtor � p � M 50.0 *Diskbr��ck i halskotpelaren med myelopati � p � 0 M 50.1 ,Diskbr��ck i halskotpelaren med radikulopati X h 0 M 50.2 !Annat diskbr��ck i halskotpelaren � p � � X M 50.3 'Annan diskdegeneration i halskotpelaren 0 `I have some questions..
This results in
all data beeing stored in a binary file (Some of the
data is stored in plain text though, but encrypted).Encrypted text is binary data.
The binary data starts and ends with ' (singlequote),In your example, where is the '
the format is hexadecimal. In your example, I cannot see any hexidecimal formatted data.
Hexidecimal would look like: ABFEFDC8214634896FA8623EDB
How can I read this fileThe same way you would read any other file.
and present all data in plain text, there is no need
to decrypt the encrypted strings though.If you cannot decyrpt the string, it is not going to be in plain text, I fear.
Do you mean you want to see a binary file as hexidecimal? -
I just can't open my emails that I get from msn. My yahoo and gmail messages work and I can open them fine but I can't open my msn mail with this computer.
Most likely you have Office 2004 which are PPC-only applications and will not work in Lion. Upgrade to Office 2011. Other alternatives are:
Apple's iWork suite (Pages, Numbers, and Keynote.)
Open Office (Office 2007-like suite compatible with OS X.)
NeoOffice (similar to Open Office.)
LibreOffice (a new direction for the Open Office suite.) -
Reading a File and diplaying in a TextField
hi,
i tried with this coding to a read line from a text file and diplay it in a text field.but this code is not working.
try
java.io.File f1=new java.io.File(sample.txt);
java.io.FileReader f2=new java.io.FileReader(f1);
java.io.BufferedReader br=new java.io.BufferedReader(f2);
java.lang.String par;
par=br.readLine();
jTextField2.setText(par);
br.close();
catch(java.io.IOException e){
jLabel4.setText("Error"+e);
can any one help me to make it work.Also the initialisation of f1 looks dodgy: do you mean sample.txt or
"sample.txt"?
Do check the file to see that it has some content. And when you assign
the string to par, output it to check you are reading what you think you
are reading:par = br.readLine();
System.out.println("Input line: " + par); -
Read a property file and store it in a hashmap
Hi,
I have tried to read a property file and store it in a hashmap. The property-names should be stored in keys and the property-values (after = symbol) in values of the hashmap. any ideas? Is it possible to do this?mandy2001ir wrote:
yes, but I need the hashmap for another reason. Actually I'm trying to use the properties file to have a dynamic hachmap. I don't want to change the code anytime I want to put a value in the hashmap. therefor I write the "keys" and "values" in a property file and change the property file. That's the reasn why we have property files, isn't it?What's a "dynamic hashmap"? There's no other kind! Whenever someone starts bandying around the word "dynamic" in contexts like this, it usually means there's a simple solution to their problem, that they haven't yet considered, or mistakenly don't believe is applicable to them, because of this "unique" need for something "dynamic". Trust me, you just need to load the file using a Properties object, and you're done. Properties extends Hashtable, which is virtually the same thing as a HashMap. Properties does exactly what you want it to. it's the very reason the class exists
Have you even looked at the javadoc for java.util.Properties yet? I'm betting not, because if you had, you'd know exactly what I meant. And since you haven't, I'm at a bit of a loss as to how you can so easily dismiss the class as useless, despite existing to do exactly what you need -
Having trouble reading specific lines from a text file and displaying them in a listbox
I am trying to read specific lines from all of the text files in a folder that are reports. When I run the application I get the information from the first text file and then it returns this error: "A first chance exception of type 'System.ArgumentOutOfRangeException'
occurred in mscorlib.dll"
Below is the code from that form.
Option Strict On
Option Infer Off
Option Explicit On
Public Class frmInventoryReport
Public Function ReadLine(ByVal lineNumber As Integer, ByVal lines As List(Of String)) As String
Dim intTemp As Integer
intTemp = lineNumber
Return lines(lineNumber - 1)
lineNumber = intTemp
End Function
Public Function FileMatches(ByVal folderPath As String, ByVal filePattern As String, ByVal phrase As String) As Boolean
For Each fileName As String In IO.Directory.GetFiles(folderPath, filePattern)
If fileName.ToLower().Contains(phrase.ToLower()) Then
Return True
End If
Next
Return False
End Function
Private Sub frmInventoryReport_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim intcase As Integer = 1
Dim strTemp, strlist, strFile As String
Dim blnCheck As Boolean = True
strFile = "Report Q" & intcase.ToString & ".txt"
Do While blnCheck = True
strFile = "Report Q" & intcase.ToString & ".txt"
Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
Dim allLines As List(Of String) = New List(Of String)
Do While objReader.Peek <> -1
allLines.Add(objReader.ReadLine())
Loop
objReader.Close()
strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
lstInventory.Items.Add(strlist)
intcase += 1
strTemp = intcase.ToString
strFile = "Report Q" & intcase.ToString & ".txt"
blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
Loop
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim intcase As Integer = 1
Dim strTemp, strlist, strFile As String
Dim blnCheck As Boolean = True
strFile = "Report Q" & intcase.ToString & ".txt"
Do While blnCheck = True
strFile = "Report Q" & intcase.ToString & ".txt"
Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
Dim allLines As List(Of String) = New List(Of String)
Do While objReader.Peek <> -1
allLines.Add(objReader.ReadLine())
Loop
objReader.Close()
strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
lstInventory.Items.Add(strlist)
intcase += 1
strTemp = intcase.ToString
strFile = "Report Q" & intcase.ToString & ".txt"
blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
Loop
End Sub
End Class
Sorry I'm just beginning coding and I'm still a noob. Any help is appreciated. Thank you!Ok, so if I'm following this correctly you should be able to just loop through all of the files in that folder whose file name matches the pattern and then read the first 22 lines, recording only the first and the last.
Exactly how you store the animal data probably depends on how you are going to display it and what else you are going to do with it. Is there anything other than name and cage number that should be associated with each animal?
You might want to make a dataset with a datatable to describe the animal, or you might write a class, or you might just use something generic like a Tuple. Here's a simple class example:
Public Class Animal
Public Property Name As String
Public Property Cage As String
Public Overrides Function ToString() As String
Return String.Format("{0} - {1}", Name, Cage)
End Function
End Class
With that you can use a routine like the following to loop through all of the files and read each one:
Dim animals As New List(Of Animal)
Dim folderPath As String = "E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\"
For Each filePath As String In System.IO.Directory.GetFiles(folderPath, "Report Q?.txt")
Using reader As New System.IO.StreamReader(filePath)
Dim lineIndex As Integer = 0
Dim currentAnimal As New Animal
While Not reader.EndOfStream
Dim line As String = reader.ReadLine
If lineIndex = 0 Then
currentAnimal.Name = line
ElseIf lineIndex = 22 Then
currentAnimal.Cage = line
Exit While
End If
lineIndex += 1
End While
animals.Add(currentAnimal)
End Using
Next
'do something to display the animals list
Then you might bind the animals list to a ListBox, or loop through the list and populate a ListView. If you decided to fill a datatable instead of making Animal instances, then you might bind the resulting table to a DataGridView.
There are lots of options depending on what you want and what all you need to do.
Reed Kimble - "When you do things right, people won't be sure you've done anything at all" -
Reading certain lines of a text file and boundary testing ...
Hi all,
This is only my second post so please be gentle ;P
Basically, my problem is that i want to read certain chunks of a text file into different text boxes. For example, this may be 50 lines in textbox1, then 50 in textbox2, then the rest in textbox3. i know this would involve using a splitter, but i have absolutelyno
idea how i would go about implementation this. any help would be greatly appreciated on this.
my second problem is that i also need to carry out testing on my system. one page in this is the login page. I understand that normal data would be all correct fields and erroneous data would be blank field(s). however, i dont really know what would be boundary
testing for this. The only thing i could think of is correct username but incorrect password but i dont think this is correct. again, any help would be appreciated.
thanks,
LTIDHi all,
This is only my second post so please be gentle ;P
Basically, my problem is that i want to read certain chunks of a text file into different text boxes. For example, this may be 50 lines in textbox1, then 50 in textbox2, then the rest in textbox3. i know this would involve using a splitter, but i have absolutelyno
idea how i would go about implementation this. any help would be greatly appreciated on this.
my second problem is that i also need to carry out testing on my system. one page in this is the login page. I understand that normal data would be all correct fields and erroneous data would be blank field(s). however, i dont really know what would be boundary
testing for this. The only thing i could think of is correct username but incorrect password but i dont think this is correct. again, any help would be appreciated.
thanks,
LTID
I suppose there would be a reason for needing to read some amount of lines into each textbox. But you make no mention of why that would be necessary.
There is such a thing as a delimited text file. Each line would contain a delimiter of some character between fields on each line. That file could be used for displaying information in separate controls on a Form.
But you only mention TextBox's and reading x amount of lines from a file into each TextBox as if you are perhaps providing certain information for each TextBox.
If that is what you want then provided replies will work. If you want to explain what you need to do with regard to information in a file and displaying it otherwise then please explain so that a better method could be provided.
Example using Text Field Parser.
https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser(v=vs.110).aspx
Option Strict On
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2)))
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("c:\Users\John\Desktop\DelimitedTextFile.Txt")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {"|"}
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
ListBox1.Items.Add(currentRow(0))
ListBox2.Items.Add(currentRow(1))
ListBox3.Items.Add(currentRow(2))
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
End Sub
End Class
Text in text file DelimitedTextFile.Txt. Delimiter is vertical bar.
Bill|Home Depot|Garden Department
Cheryll|DirectTV|Installer
Charlie|C&K Automotive|Owner
Zorro|Television|Masked Avenger
Samantha|Mayo Clinic|Nurse Practitioner
Mona|Bahia Honda Key State Park|Park Ranger
La vida loca -
Where does this java program read a text file and how does it output the re
someone sent this to me. its a generic translator where it reads a hashmap text file which has the replacement vocabulary etc... and then reads another text file that has what you want translated and then outputs translation. what i don't understand is where i need to plugin the name of the text files and what is the very first line of code?
[code
package forums;
//references:
//http://forums.techguy.org/development/570048-need-write-java-program-convert.html
//http://www.wellho.net/resources/ex.php4?item=j714/Hmap.java
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
public class Translate {
public static void main(String [] args) throws IOException {
if (args.length != 2) {
System.err.println("usage: Translate wordmapfile textfile");
System.exit(1);
try {
HashMap words = ReadHashMapFromFile(args[0]);
System.out.println(ProcessFile(words, args[1]));
} catch (Exception e) {
e.printStackTrace();
// static helper methods
* Reads a file into a HashMap. The file should contain lines of the format
* "key\tvalue\n"
* @returns a hashmap of the given file
@SuppressWarnings("unchecked")
private static HashMap ReadHashMapFromFile(String filename) throws FileNotFoundException, IOException {
BufferedReader in = null;
HashMap map = null;
try {
in = new BufferedReader(new FileReader(filename));
String line;
map = new HashMap();
while ((line = in.readLine()) != null) {
String[] fields = line.split("\\t", 2);
if (fields.length != 2) continue; //just ignore "invalid" lines
map.put(fields[0], fields[1]);
} finally {
if(in!=null) in.close(); //may throw IOException
return(map); //returning a reference to local variable is safe in java (unlike C/C++)
* Process the given file
* @returns String contains the whole file.
private static String ProcessFile(Map words, String filename) throws FileNotFoundException, IOException {
BufferedReader in = null;
StringBuffer out = null;
try {
in = new BufferedReader(new FileReader(filename));
out = new StringBuffer();
String line = null;
while( (line=in.readLine()) != null ) {
out.append(SearchAndReplaceWordsInText(words, line)+"\n");
} finally {
if(in!=null) in.close(); //may throw IOException
return out.toString();
* Replaces all occurrences in text of each key in words with it's value.
* @returns String
private static String SearchAndReplaceWordsInText(Map words, String text) {
Iterator it = words.keySet().iterator();
while( it.hasNext() ) {
String key = (String)it.next();
text = text.replaceAll("\\b"+key+"\\b", (String)words.get(key));
return text;
* @returns: s with the first letter capitalized
String capitalize(String s)
return s.substring(0,0).toUpperCase() + s.substring(1);
}without what arguments?Without any arguments. If there are no arguments, there are no arguments of any kind. If you have a zoo with no animals in it, it's not meaningful to ask whether the animals which are not there are zebras or elephants.
does it prompt me to give it a text file name?Apparently.
when i run it this is all i get:
usage: Translate wordmapfile textfile
Press any key to continue...Right. And "wordmapfile" is almost certainly supposed to be a file that holds the word map, and "textfile" is almost certainly the file of text that it's going to translate. -
Issue : Read a text file and print the same
Hi, My requirement is to read a text file and print it the same way.
import java.io.BufferedReader;
import java.io.FileReader;
public class CatFile {
public static void main(String[] args) throws Exception
FileReader file = new FileReader("D:/Test/Allfiles.txt");
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while (line != null)
text += line;
line = reader.readLine();
System.out.println(text);
The text file i used contains
A
B
C
but my output is ABC.
What change should be made to print it the same way in the txt file ?Hi EJP,
I modified the code based on your suggestion and now its working as expected. Thanks
Modified code :
import java.io.BufferedReader;
import java.io.FileReader;
public class CatFile {
public static void main(String[] args) throws Exception
FileReader file = new FileReader("D:/Test/Allfiles.txt");
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while (line != null)
System.out.println(line);
line = reader.readLine();
text += line;
} -
Read multiple text files and sort them
I am trying to read multiple text files and store the data from the file in vector.
but for days. I am with no luck. anyone can help me out with it? any idea of how to sort them will be appreciated.
Below is part of the code I implemented.
public class packet {
private int timestamp;
private int user_id;
private int packet_id;
private int packet_seqno;
private int packet_size;
public packet(int timestamp0,int user_id0, int packet_id0,int packet_seqno0, int packet_size0)
timestamp = timestamp0;
user_id=user_id0;
packet_id=packet_id0;
packet_seqno=packet_seqno0;
packet_size=packet_size0;
public void setTime(int atimestamp)
this.timestamp=atimestamp;
public void setUserid(int auserid)
this.user_id=auserid;
public void setPacketid(int apacketid)
this.packet_id=apacketid;
public void setPacketseqno(int apacketseqno)
this.packet_seqno=apacketseqno;
public void setPacketsize(int apacketsize)
this.packet_size=apacketsize;
public String toString()
return timestamp+"\t"+user_id+"\t"+packet_id+"\t"+packet_seqno+"\t"+packet_size+"\t";
}Here is the data from part of the text files. ( the first column is timestamp, second is userid, third is packetid.....)
0 1 1 1 512
1 2 1 2 512
2 3 1 3 512
3 4 1 4 512
4 5 1 5 512
5 6 1 6 512
6 7 1 7 512
7 8 1 8 512
8 9 1 9 512
9 10 1 10 512
10 1 2 11 512
11 2 2 12 512
12 3 2 13 512
13 4 2 14 512
14 5 2 15 512
15 6 2 16 512
16 7 2 17 512Here's a standard idiom for object-list-sorting:
/* cnleafdata.txt *********************************************
0 1 1 1 512
1 2 1 2 512
2 3 1 3 512
3 4 1 4 512
4 5 1 5 512
5 6 1 6 512
6 7 1 7 512
7 8 1 8 512
8 9 1 9 512
9 10 1 10 512
10 1 2 11 512
11 2 2 12 512
12 3 2 13 512
13 4 2 14 512
14 5 2 15 512
15 6 2 16 512
16 7 2 17 512
import java.util.*;
import java.io.*;
public class Packet implements Comparable<Packet>{
private int timeStamp;
private int userId;
private int packetId;
private int packetSeqno;
private int packetSize;
public Packet(int timeStamp0, int userId0, int packetId0,
int packetSeqno0, int packetSize0) {
timeStamp = timeStamp0;
userId = userId0;
packetId = packetId0;
packetSeqno = packetSeqno0;
packetSize = packetSize0;
public Packet(String timeStamp0, String userId0, String packetId0,
String packetSeqno0, String packetSize0) {
this(Integer.parseInt(timeStamp0), Integer.parseInt(userId0),
Integer.parseInt(packetId0), Integer.parseInt(packetSeqno0),
Integer.parseInt(packetSize0));
public Packet(String[] a){
this(a[0], a[1], a[2], a[3], a[4]);
public void setTime(int aTimeStamp){
timeStamp = aTimeStamp;
public void setUserId(int aUserId){
userId = aUserId;
public void setPacketId(int aPacketId){
packetId = aPacketId;
public void setPacketSeqno(int aPacketSeqno){
packetSeqno = aPacketSeqno;
public void setPacketSize(int aPacketSize){
packetSize = aPacketSize;
public int getUserId(){
return userId;
public String toString(){
return String.format
("%2d %2d %2d %2d %4d", timeStamp, userId, packetId, packetSeqno, packetSize);
public int compareTo(Packet otherPacket){
return userId - otherPacket.getUserId();
/* main for test */
public static void main(String[] args){
String line;
ArrayList<Packet> alp;
alp = new ArrayList<Packet>();
try{
BufferedReader br = new BufferedReader(new FileReader("cnleafdata.txt"));
while ((line = br.readLine()) != null){
// if (! recordValid(line)){
// continue;
String[] ar = line.split("\\s");
alp.add(new Packet(ar));
catch (Exception e){
e.printStackTrace();
System.out.println("[original]");
for (Packet p : alp){
System.out.println(p);
System.out.println();
Collections.sort(alp);
System.out.println("[sorted by user ID]");
for (Packet p : alp){
System.out.println(p);
} -
Reading multiple text files and writing them to one text file
Hi,
I'm trying to read a number of text files and write them to a single master file. My program reads all the files but only writes the last one to the master file.
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
// Input/Output Classes
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.GridLayout;
public class Actor implements ActionListener
public static String DataRoot = "I:\\JAVA\\UBP\\DAT
public static JFrame SW = new JFrame();
public static JTextField txtSPath;
public static JTextArea txtTable;
public void actionPerformed( ActionEvent e )
String Command = e.getActionCommand();
if (Command.equals("Process") )
SetupWin();
ProcessAll();
public void SetupWin()
SW.setTitle("void");
SW.setSize(300,400);
SW.setLayout(new GridLayout(6,1));
txtSPath = new JTextField(40); SW.add(txtSPath);
txtTable = new JTextArea(10, 40); SW.add(txtTable);
SW.setVisible(true);
public void ProcessAll()
Process("Dunstable","Finance");
Process("Dunstable","Production");
Process("Dunstable","Sales");
public void Process(String Town, String Dept)
String SPath = DataRoot + Town + "
" + Dept + ".txt";
String MPath = DataRoot + "masterFile" + ".txt";
txtSPath.setText(SPath);
String message = "Trying " + SPath;
System.out.println(message);
String SlaveTable=message;
try// if following fails an exception is thrown
Scanner Slave = new Scanner(new FileInputStream(SPath)); // reads slave file
PrintWriter outputStream = null;
outputStream = new PrintWriter(new FileOutputStream(MPath));
while ( Slave.hasNextLine() ) // reads text line by line
//Read and output next record
String PartRecord = Slave.nextLine();
String FullRecord = Town + " " + PartRecord;
System.out.println(FullRecord);
outputStream.println(FullRecord);
Slave.close();
outputStream.close();
txtTable.setText(SlaveTable);
//An Exception Error would be THROWN by above & CAUGHT below
catch(FileNotFoundException e)
message = "Could Not Find " + SPath;
System.out.println(message); //console
txtSPath.setText(message); //window
catch(IOException e)
System.out.println("Slave I/O Problem " + SPath);
}Edited by: Ardour on Mar 4, 2008 1:53 PMI haven't looked closely, but my spidey sense tingles at this:
new FileOutputStream(MPath)This will clobber (erase) the previous contents of the file. Open in append mode:
new FileOutputStream(MPath, true)Of course, if the file exists before you run this code, you will end up append to the original contents. If that is not wanted, consider using File's delete method first. -
Copy one text file to another text file and delete last line
Hi all wonder if someone can help, i want to be able to copy one text file to another text file and remove the last line of the first text file. So currently i have this method:
Writer output = null;
File file = new File("playerData.xml");
try {
output = new BufferedWriter(new FileWriter(file, true));
output.write("\t" + "<player>" + "\n");
output.write("\t" + "\t" + "<playerName>" + playerName + "</playerName>" + "\n");
output.write("\t" + "\t" + "<playerScore>" + pointCount + "</playerScore>" + "\n");
output.write("\t" + "\t" + "<playerTime>" + minutes + " minutes " + seconds + " seconds" + "</playerTime>" + "\n");
output.write("\t" + "</player>" + "\n");
output.write("</indianaTuxPlayer>" + "\n");
output.close();
System.out.println("Player data saved!");
catch (IOException e) {
e.printStackTrace();
}However each time the method is run i get the "</indianaTuxPlayer>" line repeated, now when i come to read this in as a java file i get errors becuase its not well formed. So my idea is to copy the original file, remove the last line of that file, so the </indianaTuxPlayer> line and then add this to a new file with the next data saved in it. So i would end up with something like this:
<?xml version="1.0" encoding="UTF-8"?>
<indianaTuxPlayers>
<player>
<playerName>Default Player</playerName>
<playerScore>0</playerScore>
<playerTime>null minutes null seconds</playerTime>
</player>
<player>
<playerName>Default Player</playerName>
<playerScore>0</playerScore>
<playerTime>null minutes null seconds</playerTime>
</player>
<player>
<playerName>Default Player</playerName>
<playerScore>0</playerScore>
<playerTime>null minutes null seconds</playerTime>
</player>
</indianaTuxPlayers>
However after all day searching the internet and trying ways, i have been unable to get anything working, could anyone give me a hand please?I would go the XML route too, but for fun, open a file as a BufferedWriter and do this:
void copyAllButLastLine(File src, BufferedWriter tgt) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(src));
try {
String previous= in.readLine();
for (String current = null; (current = in.readLine()) != null; previous=current) {
tgt.write(previous);
tgt.newLine();
} finally {
in.close();
} -
Searching a text file and printing the line if found!
Hi, Im fairly new to JAVA and have been googling this for hours and havent found any results that
have helped me...
Im looking to search a text file for a value that is in a that is delimited by colons
eg 45787 : 398948 : 398884 : 398984
IF that value is found I need to print this entire line and move it into a string.
I can work out the delimit part, the problem for me is a)searching the text file
and b) tell java to print that line only??
Any help would be very very much appreciated
Cheers
Jamespublic void printCourses() throws Exception
stuinput[] courseObjArray = new stuinput[10]; //Make sure this is the same as the ammount in the text
Scanner sc = new Scanner(new File("testfile.txt"));
int i=0;
boolean found = false;
while(sc.hasNextLine())
//Delimit this line with scanner
Scanner sc1 = new Scanner(sc.nextLine());
sc1.useDelimiter(":");
courseObjArray[i] = new stuinput(sc1.next(),sc1.next());
i++;
}//while
for(int i1 = 0;i1 < courseObjArray.length;i1++)
System.out.println(courseObjArray[i1].courseCode);
System.out.println(courseObjArray[i1].courseName);
System.out.println(courseObjArray[i1].courseName);
System.out.println("-----------------");
String courseCode2 = "courseObjArray[i1].courseCode";
if (courseCode2 == "12345")
System.out.println("working");
else{System.out.println("Not Found");}
}hmmm just wondering why could this method always return a "Not Found"....if the text file had a whole bunch of values like this
12345:Course1
12344:Course2
12343:Course3
isnt it surposed to return 1 "Working"?? because there is a 12345 in on of the line, in the semi colon delimited line with 2 values, one being the course code, one being the course name??
Given that there is 10 lines (from Array Object)
Maybe you are looking for
-
How to solve the dn collision in AD during AD account provisioning
Hello, I have multiple users with the same last name, first name and middle name. We decided to build the full name using the rule: lastName, firstName OR lastName, firstName# (if the lastName, firstName already exists, add a number and the number ju
-
Photoshop CS6 continually crashes on save
I know I'm not the only one with this issue. I got rid of my most recent preferneces already and uninstalled my last extension but still am crashing on almost every save! Can anybody see the issue? Thanks much. Here is the log: Process: Adobe Pho
-
How can I import address book info from old mac to new one?
Just got a macbook, and migrated all the info as per instructions. Now I need to get all the info from my old address book to the new one. Spent about 6 hours today trying to figure this out, and an hour of that was spent on the phone with a friendly
-
No sleep after installing recent java, daylight savings & security updates
After installing the recent java, daylight savings, and the security update, my computer would crash and upon startup would act funny showing a b&W screen with typewriter type asking me to keyboard in directions ie. "shut-down". I was able to reset t
-
Extracting the card code (vendor code) from form 133
hi all. im kinda new in SBO sdk and im trying to extract the data from form 133 item 4 = cardcode i tried this code SAPbouiCOM.Item oItem = null; oItem = oForm.Items.Item("4"); SAPbouiCOM.C